The paradigm for tying in an input field to the state is pretty clean-
First you get the local variable and a way of changing it:
const [name, setName] = useState('');
Then you render an input field like this:
<input value={name} onChange={(e) => setName(e.target.value)} />
I ran into a gotcha with a react-modal component, one that is effectively reused across the life of the parent component. Using something like
const [name, setName] = useState(props.name);
wouldn't reset things so to speak - name was being reset to the initial value from the first render even as the props were updated and the entire component was being re-rendered.
The solution is to combine it with the useEffect hook to get that side effect action going:
Once you've called useState, do something like
useEffect(() => {
setName(props.name ? props.name : '');
}, [props]);
That let the inputs have the right initial value while still updating the local state as the user typed.
No comments:
Post a Comment