React - form example (controlled components)

3 points
Created by:
Dirask Community

In this article we would like to show you how to use React forms.

Below example shows how to make a form as an 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 update the state.

Quick solution:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from react';
const Form = props => {
    const [username, setUsername] = React.useState();
    const [password, setPassword] = React.useState();
    const handleSubmit = e => {
        const data = {
          username, password
        const json = JSON.stringify(data, null, 4);
    return (
      <form onSubmit={handleSubmit}>
          <label>Username: </label>
          <input type="text" value={username}
            onChange={e => setUsername(} />
          <label>Password: </label>
          <input type="password" value={password}
            onChange={e => setPassword(} />
        <button type="submit">Submit</button>

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.


Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

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