I have a child component which contains a custom switch using Bootstrap 4 (see here: https://www.w3schools.com/bootstrap4/bootstrap_forms_custom.asp). If the value changes the value should be passed to parent component using a callback function and then it should update the parent“s state.
The data flow itself is working properly, the only problem is, that the wrong value is sent. As initial value the switch has false. After toggling the switch the value should be true, but the value of false is passed to the parent.
Here are my components:
Parent component:
class Questionnaire extends Component {
constructor(props) {
super(props);
this.state = {
review: false
};
}
sendData = childData => {
this.setState({
review: childData
});
}
render() {
return(
<div className="container">
<Question sendData={this.sendData}/>
</div>
);
}
}
And here my child component:
class Question extends Component {
constructor(props) {
super(props);
this.state = {
example: false
};
}
onChangeSwitch = () => {
this.setState({
example: !this.state.example
});
this.props.sendData(this.state.example);
}
render() {
return(
<div className="custom-control custom-switch">
<input type="checkbox" className="custom-control-input" id="switch" checked={this.state.example} onChange={this.onChangeSwitch}/>
<label className="custom-control-label" htmlFor="switch">Do you like milk?</label>
</div>
);
}
}
Summing up: At initial state the switch has the value false. After clicking on the switch, the value changes to true and updates the children“s state, which is intented to be passed to the parent via callback. In fact the old state (false) of the children is passed to the child component. Thank you very much for helping out!