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!
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:
https://www.simplilearn.com/tutorials/reactjs-tutorial/reactjs-state#:~:text=1%20A%20state%20can%20be%20modified%20based%20on,merge%20between%20the%20new%20and%20the%20previous%20state
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>
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