Matiny
Matiny

Reputation: 179

Using react, how can I create a function to set the state that takes the state name and value as arguments?

I have a simple app that will be keeping track of lots of different states.

I realize that I can create a function that is something like...

   changeSomething = (nameOfState) => {
     this.setState({nameOfState});
   }

And I'll have a reusable function for this.state.nameOfState. In this case, I need to set up a reusable function for numerous states. This is b/c initially, I only had 3 states so I didn't care. Now I'm going to have about 10 setstate functions, so it makes no sense to copy and paste 10 times. I should be able to make a reusable function which takes the state name and value as arguments and sets them.

Upvotes: 0

Views: 34

Answers (3)

Jayabalaji J
Jayabalaji J

Reputation: 1066

send the param as object with state name as key to the value.

Eg:

changeSomething({ yourStateName: yourValue }) // function called with parameters as object
changeSomething = (stateValue) => {
    this.setState ({ stateValue });
}

Upvotes: 1

Marian Gibala
Marian Gibala

Reputation: 884

You can use square brackets to dynamically create prop name.

 changeSomething = (nameOfState, value) => {
     this.setState({[nameOfState]: value});
   }

Then just define your prop name when binding function to event. For example:

<SomeComponent onChange={this.changeSomething.bind(null, 'propName')} />

Here is JSFiddle example for you: https://jsfiddle.net/g64jx6dn/1/

Upvotes: 1

Daniel Tran
Daniel Tran

Reputation: 6171

You can do something like this:

changeSomething = (stateName, value) => {
     this.setState({[stateName]: value});
}

Upvotes: 1

Related Questions