How to Develop User Registration Form in ReactJS ?

10 Jan, 2022
Form is usually defined inside the <form> tag in conventional HTML code and also in ReactJS. It can have the usual form submission behavior that can take to a new page but that will not make use of react full potential, instead, as we all know it is done using react components.
Approach: As we all know React is famous for the components and hooks and its reusability, we are going to use the component to create a form. This form component just like an ordinary HTML form can have labels, input fields, text area, radio button, check box, etc. On top of that, it can also have different attributes with little modification i.e. “for” attribute is replaced by “htmlfor”, “class” is replaced by “className”. It still can have some of the old practices such as “value” property is still there.
As we are having the strength of React, we will handle the form by creating different methods for that i.e. to handle the change in any field of the form there will be a method when submit button is clicked there will be a method for it, likewise.
We will not hold the value received by the form in a normal JavaScript variable instead we will use high-powerful react hooks. i.e. useState hook. For that let us, first of all, see how we can use this useState hook with form.
Using useState with the form data: Every component can have its own states, these states can be updated using the hook useState and the effect will be reflected through the component.
Here, the “name” has been given to be the state variable and it has an initial value as “GFG”. We have also given the property onChange which is used to specify the method that should be executed whenever the value of that input field is changed, we have set it to the handleChange, which is yet to define as shown below.
Javascript
import React,{useState} from 'react' export default function test() {     const [name, setName] = useState("GFG");         // HandleChange method to update the states    const handleChange = () => ();         return (        <div>            <form>                <input value={name} onChange={handleChange}/>            </form>        </div>    )}
  
Example: Now, let us extend our understanding of useState hook by creating the user form, which will take name, email, and password as the input. It will have one submit button to handle the submission. We will also validate the fields, if either of the fields is empty we will show an error message if not we will show a success message to the user.
 
Create React Application: Create a React application using the following command.
 
npx create-react-app yourappname
Project Directory: Then in your “src” folder erase the content of App.css and App.js files and also create one more file named Form.js, finally, your project structure will look like this.
 
Project Structure
Filename: App.css This file contains all the CSS that we need for this example which is not only self-explanatory but also out of the scope of this article. Although it is given here for your reference.
 
CSS
.App {  text-align: center;  background-color:green;} .label{  display: block;  font-size: larger;  color: white;  padding: 5px;} .input{  font-size: larger;  padding: 5px;  margin: 2px;  }.btn{  color: white;  background-color: red;  border-radius: 5px;  font-size: larger;  display: block;  padding: 5px;  margin: 10px auto;} .messages{  display: flex;  justify-content: center;} .error{  display: block;  background-color: red;  color: white;  width: fit-content;  height: 50px;  padding: 5px;} .success{  display: block;  background-color: lightblue;  color: black;  width: fit-content;  height: 50px;  padding: 5px;}
  
Filename: App.js This App.js is the file, which is being rendered by React by default in the index.js file, we will not touch that index.js file, instead all our components which we make will be rendered inside this App.js as shown below.
 
Javascript
import './App.css';import Form from "./Form" function App() {  return (    <div className="App">      <Form />    </div>       );} export default App;
  
Filename: Form.js This file has all the necessary components, functions for our form. First of all, we have imported useState from the react. then we have exported the form component which is having all the states and methods.
 
We have defined states for name, email, and password for holding form data. We also have some other states such as submitted and error for the functionality of the form. Then, we have defined the handleName, handleEmail, handlePassword methods which are used to update the states. 
 
After that, we are having a method for handling the submission of the form. It is checking if either of the fields is empty it set errors to true, otherwise, it sets success to true. Then we have defined a success message, which is only displayed if the success is set to true. Then we have an error message which is only displayed if an error is set to true.
 
Then we are returning the component, first of all, we have an h1 to hold the heading of the form. Then we have one division to hold the successMessage() and errorMessage(). And at last, the division which holds the form. It has usual labels and input fields. The onChange to give their respective methods and their value to associate them with the states.
 
Note: The states can only be updated using set methods as shown in the methods.
 
Javascript
import { useState } from 'react'; export default function Form() {   // States for registration  const [name, setName] = useState('');  const [email, setEmail] = useState('');  const [password, setPassword] = useState('');   // States for checking the errors  const [submitted, setSubmitted] = useState(false);  const [error, setError] = useState(false);   // Handling the name change  const handleName = (e) => {    setName(e.target.value);    setSubmitted(false);  };   // Handling the email change  const handleEmail = (e) => {    setEmail(e.target.value);    setSubmitted(false);  };   // Handling the password change  const handlePassword = (e) => {    setPassword(e.target.value);    setSubmitted(false);  };   // Handling the form submission  const handleSubmit = (e) => {    e.preventDefault();    if (name === '' || email === '' || password === '') {      setError(true);    } else {      setSubmitted(true);      setError(false);    }  };   // Showing success message  const successMessage = () => {    return (      <div        className="success"        style={{          display: submitted ? '' : 'none',        }}>        <h1>User {name} successfully registered!!</h1>      </div>    );  };   // Showing error message if error is true  const errorMessage = () => {    return (      <div        className="error"        style={{          display: error ? '' : 'none',        }}>        <h1>Please enter all the fields</h1>      </div>    );  };   return (    <div className="form">      <div>        <h1>User Registration</h1>      </div>       {/* Calling to the methods */}      <div className="messages">        {errorMessage()}        {successMessage()}      </div>       <form>        {/* Labels and inputs for form data */}        <label className="label">Name</label>        <input onChange={handleName} className="input"          value={name} type="text" />         <label className="label">Email</label>        <input onChange={handleEmail} className="input"          value={email} type="email" />         <label className="label">Password</label>        <input onChange={handlePassword} className="input"          value={password} type="password" />         <button onClick={handleSubmit} className="btn" type="submit">          Submit        </button>      </form>    </div>  );}
  
Run the application using the following command:
 
npm start
Output:
 
Output
References: https://reactjs.org/docs/forms.html
 
sratcliffjones
rkbhola5
CSS-Properties
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
Re-rendering Components in ReactJS
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React