Reputation: 323
I am learning React. I read an article that suggests us to use functional component instead of class that extends React.Component, so I followed. I also use the arrow function instead of function keyword. That is:
const MyComponent = (props) => {...}
I got a structure that has 20 properties like:
{
id: '',
firstname: '',
lastname: '',
...
}
I am using if ... else if ... to set the state, but I saw some examples that use this.setState() in just one line of code. I try to import setState from 'react', but fail.
Is there a way to use setState() instead of setName(), setId(), ..., etc? Or any suggestion?
Thank you very much!
Upvotes: 16
Views: 61449
Reputation: 43
Class-based components and functional components both have different ways of storing and setting values in them.
In class-based components, this.state is used which is usually of an object nature and holds all the values needed in the components, here setState() function is used to do a shallow update to this.state object. (It will merge the prev and new object)
In function-based components state can be stored using useState hook. The name of the state variable can be anything. Just like the class component here, we have two items returned by the useState hook. The first item represents the variable and the second represents the setter function.
Now,
To useState variable is declared like,
const [banana, setBanana] = useState("initial value - could be string, number, object");
To use the variable in the component just use the variable name "banana" and set a new value in the variable using the setter function like,
setBanana("good banana");
This will change the initial value to whatever you set it to. If the variable was an object, it will be replaced by the new object not shallow merged.
Also, inside a function-based component, you can have any number of useState variables. The important thing to keep in mind is if multiple of them are called in a function call batching is performed.
Refs:-
Upvotes: 0
Reputation: 214
this.setState only works in class based components. In functional components useState hook is used which behaves as a state
useState lets you add React state to function components.
Upvotes: 4
Reputation: 488
There is only the (one) 'setState()' method - not a method per-property (as you've suggested/questioned).
It is a composite in terms of it's parameter, in that you can specify/set more than one item within the same/one call (to the 'setState()' method), so you can set all 20 of your items in one go.
E.g.
this.setState({ "firstName" : firstNameVal, "lastName" : lastNameVal });
I was starting from where you said you started - from a 'class' based component.
If you are sticking with the switch to a 'function' based component, then it is slightly different, in summary:
import React, { useState } from 'react';
...
// The 'useState' hook (function) returns a getter (variable) & setter (function) for your state value - and takes the initial/default value for it/to set it to, e.g.
const [ firstName, setFirstName ] = useState('');
And you then use the getter var to read it & the setter function to set it:
setFirstName('Dennis');
(I could be wrong but I believe 'hooks' were added in v16.8 of React.)
A more in-depth description:
Upvotes: 9
Reputation: 11011
Use useState
hook in functional components.
const App = () => {
const [state, setState] = React.useState({ first: "hello", second: "world" });
return (
<div>
<input type="text" value={state.first} onChange={(ev) => setState({...state, first: ev.target.value})} />
<input type="text" value={state.second} onChange={(ev) => setState({...state, second: ev.target.value})} />
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="app"> </div>
Upvotes: 8