React - form with useState example (controlled components)
In this article, we would like to show you how to use React forms with useState
hook.
The below example shows how to make a form
as a functionalĀ controlled component.
It's a simple form
with two inputs: username
, password
and submit
button.
With useState
we are able to keep the data inĀ component'sĀ state - in our case it's username
and password
. When onChange
event occurs thenĀ setUsername
and setPassword
Ā are used to update theĀ state
.
undefined
value
property switches input
into the uncontrolled mode, so it is very important to set an empty stringĀ as initial states and later use them as not set values toĀ prevent switching across controlled and uncontrolled component modes.
Quick solution:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const Form = () => {
const [username, setUsername] = React.useState('');
const [password, setPassword] = React.useState('');
const handleSubmit = e => {
e.preventDefault();
const data = {
username, password
};
const json = JSON.stringify(data, null, 4);
console.clear();
console.log(json);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Username: </label>
<input type="text" value={username}
onChange={e => setUsername(e.target.value)} />
</div>
<div>
<label>Password: </label>
<input type="password" value={password}
onChange={e => setPassword(e.target.value)} />
</div>
<button type="submit">Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );
Important note:
When you create forms, React recommends using uncontrolled components,
because with controlled components large amount ofĀ inputĀ elements withonChange
event handling leads to performance degradation by component multiple re-rendering.Read this article to see uncontrolled version.