Languages
[Edit]
EN

React - form example (controlled components)

3 points
Created by:
Dirask Community
1700

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 => {
        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.

ReactJS

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

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

Join