Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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}/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading