Languages
[Edit]
EN

React - form reset (class component)

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you how to reset forms in React.

Below example shows a form with two inputs. To store data we use the component's state. To reset the form we need to reset the state by setting its properties to '' (empty string) using setState() method.

Practical example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
  }

  handleReset = e => {
    this.setState({ username: '', password: '' })
  }

  render() {
    return (
      <form onSubmit={e => e.preventDefault()}>
        <div>
          <label>Username: </label>
          <input type="text" value={this.state.username}
            onChange={e => this.setState({ username: e.target.value })} />
        </div>
        <div>
          <label>Password: </label>
          <input type="password" value={this.state.password}
            onChange={e => this.setState({ password: e.target.value })} />
        </div>
        <button onClick={this.handleReset}>Reset</button>
      </form>
    );
  }
};

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root);

Better solution:

In this solution, we store the state of each input in one data object inside the component's state. That object contains properties named the same as input properties ("username" and "password"). Input properties will be cleared by overriding the data with an empty object using setState() method. To prevent setting null and undefined values we used ?? operator with '' as alternative value.

Note:

In this example we use new features introduced in ES2020 (ECMAScript 2020).
Go here to read more about ?. operator and Optional Chaining in ES2020.

Practical example: 

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {}
    };
  }

  handleChange = e => {
    const target = e.target;
    this.setState({ data: { ...this.state.data, [target.name]: target.value } });
  };

  handleReset = () => this.setState({ data: {} });

  render() {
    return (
      <form onSubmit={e => e.preventDefault()}>
        <div>
          <label>Username: </label>
          <input type="text"
            name="username" value={this.state.data?.username ?? ''}
            onChange={this.handleChange} />
        </div>
        <div>
          <label>Password: </label>
          <input type="password"
            name="password" value={this.state.data?.password ?? ''}
            onChange={this.handleChange} />
        </div>
        <button onClick={this.handleReset}>Reset</button>
      </form>
    );
  }
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

ReactJS

React - form reset (class component)
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