Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How setState with one value work?

I was looking through some code while using the npm package React-Select

Interestingly enough i saw setState being used as such:

handleSelectChange (value) {
        console.log('You\'ve selected:', value);
        this.setState({ value });
    },

How does setState work like this? It only provides one value? I am asking because I would like to perhaps capture one thing from my input and then change it. But that doesn't work as intended.

handleSelectChange (value) {
        console.log('You\'ve selected:', value);
        this.setState({ value.name });
    },

The full code is here, its fairly short: https://github.com/JedWatson/react-select/blob/master/examples/src/components/Multiselect.js

like image 766
ApathyBear Avatar asked Mar 25 '26 11:03

ApathyBear


1 Answers

When using in ES6

this.setState({ value })

It is just a shorthand for

this.setState({ value: value })

There's nothing else magical happening here


For more clarity, consider this example

var x = 5
var y = 10
var z = { x, y }
console.log(z)
//=> { x: 5, y: 10 }

If you want to set the state to value.name you would not be able to use the shorthand if the key you had to set was still called value

this.setState({ value: value.name })
like image 69
Mulan Avatar answered Mar 27 '26 01:03

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!