I am passing the name and value to handleChange function from child component.
Now I want to set the state to the value that matches the provided name. But I do not know how to set it.
I tried this way(but it gives error - 'this.setState is not a function') :
class ParentComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
this.state = {
loanAmount: 348600.48,
numberOfYears: 70,
}
handleChange(name, value) {
this.setState({ name: value },() => {
this.financeCalcualte();
});
}
The code of the child component is:
onChange = (event) => {
const {name, rawValue} = event.target;
this.props.handleChange(name, rawValue)
}
What is the correct syntax to set it?
In order to use this in a callback function, as told in the comments you have to bind it in the constructor or use an arrow function.
Also, since your name is a variable, you can't update your state like:
this.setState({ name: value }
because this creates a name property in your state, does not update the state variable which has the name as your incoming variable. So, you should use a computed property.
handleChange = (name, value) =>
this.setState({ [name]: value }, () => this.financeCalcualte());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With