Home > other >  What's the best way to get input value in React
What's the best way to get input value in React

Time:04-21

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.

CodePudding user response:

Don't use vanilla DOM manipulation in React when you can avoid it, within reason. The first approach is far better in most situations.

  • Working with the DOM is slow. State and the virtual DOM help a lot.
  • In the React paradigm, the appearance and functionality of the application should ideally stem from state as much as possible. Non-stateful side-effects can make things difficult to reason about and hard to work with given how re-rendering works and should be avoided.

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}/>
  • Related