Button Component (Child)
export default class Button extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (
<button onClick={() => handleToUpdate(this.id)}>
{this.props.title}
</button>
);
}
}
Index(Parent)
in return
<Button title={title1} handleToUpdate={handleToUpdate.bind(this)} />
<Button title={title2} handleToUpdate={handleToUpdate1.bind(this)} />
<Button title={title3} />
<Button title={title4} />
in render
const title1 = "test1"
const title2 = "test2"
const title3 = "test3"
const title4 = "test4"
var handleToUpdate = this.handleToUpdate;
var handleToUpdate1 = this.handleToUpdate1;
function
handleToUpdate() {
this.setState({})
}
handleToUpdate1() {
this.setState({})
}
var handleToUpdate = this.handleToUpdate.bind(this);
var handleToUpdate1 = this.handleToUpdate1.bind(this);
There is no issue in my code but my way of approaching to the function is not good practice I believe.
What I am doing here is I made button component(Child) and calling it four times in the parent(index). I created onClick
props to call function and then set state.
Is there any alternative method that I can create one function with 4 setState
and call the state according to the button id which is clicked.
To Make it more clear.
Button 1 clicked => call singlefunction => setstate1
Button 2 clicked => cal singlefunction => setstate 2 ...
id
?(this.id)