Develop User Registration Form in React JS



Developing user registration forms in ReactJS is easier said than done. This is because the process entails detecting unregistered users, acquiring authorization from registered users, and registering new users. Fortunately, react offers a convenient method for executing the user registration process in just a few steps.

Prerequisites

A few things you ought to have before you can start developing your user registration form.

  • Basic knowledge of how hooks work in React to simplify state management and side effects. Common hooks you ought to familiarize yourself with include the ?useState' and ?useEffect' (for additional effects) hooks.
  • Advanced HTML and CSS knowledge will help you design more appealing and effective user registration forms.

Project Structure

There is no need to create any file or directory we will work on the default project structure.

Project Structure

Approach

The section below will attempt to address the project structure tasks, starting with the initial steps as you advance through the completion of the project.

Step 1: Creating a New React App

Creating your new React app is as simple as pasting the code below, and substituting the ?user-registration-form' section with your preferred project name.

npx create-react-app user-registration-form
Step 2: Start the Development Server

This is where you are expected to initialize your development server by pasting the following code in your terminal.

cd user-registration-form

npm start

The server ought to be running on http://localhost:3000 on your default browser.

Step 3: Creating the Registration Form Component

This is a two-fold process that requires you to define the RegistrationForm component before using the useState hook to develop the form of state management.

Step 4: Designing the Form Layout

This stage involves the process of creating the input and label elements using ReactJS. For example, you can use the following field if your project has a similar field range.

  • Full Name
  • Email Address
  • Password
  • Confirm Password

The fields above cover the standard new user registration fields and are sufficient in our example.

Step 5: Handling the Form State

In this section, you can initialize the state variables from your fields by using the useState component. You can then proceed to bring the input fields to state the variables with the onChange handlers.

Step 6: Validating the Form

The essence of validating the form is to ensure your users enter the correct details in the respective input fields. In our case, let us implement basic validation checks that ensure that all fields are filled, the email format is correct, and the passwords match. It is standard practice for error messages to appear on screen whenever there is an invalid input.

Step 7: Submitting the Form Data

You can create a handleSubmit function in your React code to process the form data. The other steps to undertake include preventing the default form submission behavior and displaying a success message or handling the form date (for example: sending it to the server).

Step 8: Optional Enhancements

You can style the 'InLine' style or libraries like 'styled-components' to customize the CSS style according to your preferences. It is recommended that you add responsiveness and visual appeal elements to enhance the user experience.

Optional validation features like the reCAPTCHA are helpful if you want to secure the integrity of your database. You can utilize libraries like Formik or Yup to execute the task and add extra features like loading spinners to spruce up the visual appeal.

Example

App.js Below is a complete working ReactJS code you can paste into your App.js folder.

import React, { useState } from 'react';
// Import the CSS file
import './index.css'; 

function App() {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
  });

  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (formData.password !== formData.confirmPassword) {
      setErrorMessage('Passwords do not match!');
      setSuccessMessage('');
    } else {
      setErrorMessage('');
      setSuccessMessage('Registration Successful!');
    }
  };

  return (
    <div className="form-container">
      <h2>User Registration</h2>
      <form className="registration-form" onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="username">Username:</label>
          <input
            type="text"
            id="username"
            name="username"
            value={formData.username}
            onChange={handleChange}
            required
          />
        </div>

        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            required
          />
        </div>

        <div className="form-group">
          <label htmlFor="password">Password:</label>
          <input
            type="password"
            id="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            required
          />
        </div>

        <div className="form-group">
          <label htmlFor="confirmPassword">Confirm Password:</label>
          <input
            type="password"
            id="confirmPassword"
            name="confirmPassword"
            value={formData.confirmPassword}
            onChange={handleChange}
            required
          />
        </div>

        {errorMessage && <p className="error-message">{errorMessage}</p>}
        {successMessage && <p className="success-message">{successMessage}</p>}

        <button type="submit" className="submit-button">Register</button>
      </form>
    </div>
  );
}

export default App;

Index.css Here are the accompanying CSS styling you can place in your relevant styles.css folder.

/* Container for the form */
.form-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

/* Heading */
h2 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

/* Form group container */
.form-group {
  margin-bottom: 20px;
  text-align: left;
}

/* Label styles */
label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

/* Input styles */
input {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

/* Input focus styles */
input:focus {
  border-color: #007bff;
  outline: none;
}

/* Button styles */
.submit-button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  font-size: 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

/* Button hover effect */
.submit-button:hover {
  background-color: #0056b3;
}

/* Error message */
.error-message {
  color: red;
  font-size: 14px;
  margin-top: -10px;
  margin-bottom: 15px;
}

/* Success message */
.success-message {
  color: green;
  font-size: 14px;
  margin-top: -10px;
  margin-bottom: 15px;
}

Output

Below is an output display you can expect after executing your new user registration form code.


Conclusion

Here in this article we have created a registration form and added a few extra features like captcha and form validation. ReactJS is an efficient tool for creating your ideal new user registration form using just a few lines of code.

Nickey Bricks
Nickey Bricks

Technical Writer

Updated on: 2024-09-12T14:12:04+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements