React update state on click
In this case, I would add onClick
handler to LinksPage
component.
class Links extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e) {
// here you know which component is that, so you can call parent method
this.props.update(this.props.data.id);
}
render() {
return (
<li>
<p>{this.props.data.name}</p>
<p>{this.props.data.vote}</p>
<button onClick={this.onClick}>Up</button>
</li>
);
}
};
And change your update
function:
class LinkListPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
data: MOCKDATA
};
this.update = this.update.bind(this);
}
update(itemId) {
// TODO: find and update your item, you can do it since you have an 'id'
const data = [...];
this.setState({
data,
});
}
}
//pass link id to update method in the LinkListPage component. ref point read this for handling the update for deep understanding https://www.sitepoint.com/immutability-javascript/
//use immutablejs or es6 in the update method cause state is immutable in react
update(id) {
//find and update your item, you can do it since you have an 'id'
//follow link: http://codereview.stackexchange.com/questions/43438/writing-a-function-to-add-or-modify-an-existing-object-inside-an-array
// this.setState({
// data:
// })
}
const Links = (props) => {
return (
<li>
<p>{props.data.name}</p>
<p>{props.data.vote}</p>
<button onClick={() => props.update(props.id)}>Up</button>
</li>
);
};