Languages
[Edit]
EN

React - form with useState example (controlled components)

8 points
Created by:
Dirask Community
6240

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 with onChange event handling leads to performance degradation by component multiple re-rendering.

Read this article to see uncontrolled version.

ReactJS

React - form with useState (controlled components)
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join