Saturday, December 28, 2024
Google search engine
HomeLanguagesHow to Develop User Registration Form in ReactJS ?

How to Develop User Registration Form in ReactJS ?

The 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 it to a new page but that will not make use of React’s full potential, instead, as we all know it is done using react components.

Approach: React is renowned for its reusable components and powerful hooks, making it an excellent choice for building forms. Just like a traditional HTML form, a form component in React can include labels, input fields, text areas, radio buttons, checkboxes, and more. With slight modifications, we can use familiar attributes such as “for” (replaced by “htmlFor”) and “class” (replaced by “className”). Additionally, React maintains the use of the “value” property.

One of React’s strengths lies in its ability to handle forms through dedicated methods. These methods can handle field changes, form submissions, and more. Rather than storing form data in a regular JavaScript variable, we can utilize the powerful useState hook provided by React.

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 the useState hook by creating the user form, which will take the name, email, and password as 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 that 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, and functions for our form. First of all, we have imported useState from the react. then we 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, and 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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments