Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState from function parameter in React [duplicate]

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?

like image 964
Rachit Gupta Avatar asked Nov 28 '25 19:11

Rachit Gupta


1 Answers

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());
like image 149
devserkan Avatar answered Dec 01 '25 07:12

devserkan