Reputation: 2753
I have the following class Component which reads data from localstorage.
The Localstorage has an array of objects. Those objects are rendered in a list as you can see below. In each list item there is a button I added in the code. If a user clicks the <ExtendButton />
I want to extend the {el.infoDays}
of 7 days.
Can anyone help me with that, or at least with binding the button to the object it is in, so that if a user clicks the button I will get the whole object (where the button is in) displayed in the console.log?
I tried the following, I tried with e.target
, this
, etc. The onExtendBtnClick
method is not well written.
let uniqid = require('uniqid');
class History extends Component {
state = {
loans: []
};
componentDidMount() {
const rawInfos = localStorage.getItem('infos');
const infos = JSON.parse(rawInfos);
this.setState({
infos: infos
});
}
render() {
const {infos} = this.state;
return (
<Container>
<Header />
<div>
<ul>
{infos.map((el) => (
<li key={uniqid()}>
<small>Requested date: {el.infoRequestTime}</small><br />
<div>
<span ><em>Requested amount</em><em>{el.infoAmount} €</em></span>
<span><em>In days</em><em>{el.infoDays}</em></span>
</div>
<spa>Give back: {el.infoCost} €</span>
<ExtendButton />
</li>
))}
</ul>
</div>
</Container>
);
}
}
export default History;
And I have also the button component:
class ExtendButton extends Component {
onExtendBtnClick = () => {
console.log(this)
};
render() {
return (
<button
className="extend-button"
onClick={this.onExtendBtnClick}
>
Extend for 1 week
</button>
);
}
}
export default ExtendButton;
Upvotes: 0
Views: 1259
Reputation: 11591
Have your button component take in an onClick
prop and set that on its own internal button:
class ExtendButton extends Component {
onExtendBtnClick = () => {
this.props.onClick();
};
render() {
return (
<button
className="extend-button"
onClick={this.onExtendBtnClick}
>
Extend for 1 week
</button>
);
}
}
Then just pass an onClick
function to your component:
<ExtendButton onClick={() => {console.log(el)}} />
Upvotes: 1