Languages
[Edit]
EN

React - form reset

3 points
Created by:
Jan-Alfaro
281

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

Below example shows a form used inside the functional component with two inputs: username and password.

To store data we use useState hook for each input element. To reset state it is necessary to set '' (empty string) using setUsername and setPassword functions.

Practical example:

// ONLINE-RUNNER:browser;

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

const Form = () => {
	const [username, setUsername] = React.useState();
	const [password, setPassword] = React.useState();
	const handleReset = e => {
		setUsername('');
		setPassword('');
	}
	return (
	  <form onSubmit={e => e.preventDefault()}>
	    <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 onClick={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. That object contains properties named same way like input properties ("username" and "password"). Input properties will be cleared by overriding the data with an empty object by setData({}). To prevent against 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';

const Form = () => {
	const [data, setData] = React.useState({}); // initially empty object
	const handleChange = e => {
		const target = e.target;
		setData({ ...data, [target.name]: target.value });
	};
	const handleReset = () => setData({});
	return (
	  <form onSubmit={e => e.preventDefault()}>
	  <div>
	    <label>Username: </label>
	    <input type="text"
	           name="username" value={data?.username ?? ''}
	           onChange={handleChange} />
	    </div>
	    <div>
	      <label>Password: </label>
	      <input type="password"
	             name="password" value={data?.password ?? ''}
	             onChange={handleChange} />
	    </div>
	    <button onClick={handleReset}>Reset</button>
	  </form>
	);
};

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

ReactJS

React - form reset
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