Today I was practicing with React and found two ways to get input values when submitting form.
First: Using hooks, for example:
...
const [name, setName] = useState('');
...
return <input onChange={(value) => setName(value)} value={name} />
Second: Get by using event.target.children[i].value, for example:
const handleSubmit = (event: BaseSyntheticEvent) => {
event.preventDefault();
const formInputs = event.target.children;
for (const input in formInputs) {
console.log(formInputs[input].value);
}
};
The question is, which one should I use and why? Is it optional, or I don't know, it does have some performance impact.
Don't use vanilla DOM manipulation in React when you can avoid it, within reason. The first approach is far better in most situations.
If the reason you're tempted to go with the second approach is that you have a whole lot of inputs and making a separate state for each is tedious, one option is to make the state be a single object (or Map) instead.
const MyInput = ({ name, state, onChange }) => (
<Input name={name} onChange={onChange} value={state[name]} />
);
const onChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value });
};
<MyInput name="name" state={state} onChange={onChange}/>