For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentBuilding a sign-up form using React

Building a sign-up form using React

Published
12th Oct, 2023
Views
view count loader
Read it in
12 Mins
In this article
    Building a sign-up form using React

    Web forms on your website might be really useful. They can be used to collect information about future consumers or to provide a quick way for current customers to inquire for assistance. On the other hand, they might be a source of various annoyances. Spam is an ever-increasing problem, and having web forms on your site invites spammers from all over the world to clutter your inboxes with junk.  For more information, check out Full Stack Bootcamp.  

    Forms are everywhere

    A web form is a great way for your visitors to contact you and transmit information to you, such as an order, a catalogue request, or even a query, which is then sent on to your database.

    On certain websites, the information provided via web forms is sent directly to the company e-mail. Web forms are created using programming languages such as PHP, HTML, or Java. Successful implementation of the code is important to the form's success.

    A signup page is one of the most common forms you will find on a website. The use of Signup and Sign in forms are common on websites to collect the details of visitors. These days, every site uses registration and login forms to maintain authentication.

    With a Signup form, users can create an account and can enjoy private space on your application, whereas a Login form validates your presence in the system while presenting you with a variety of alternatives to see and process.

    In this article, we'll learn how to make a simple signup page with React and Material-UI. Our application will include a button that will launch a modal with a form. This is the type of form you typically encounter on several websites. It will have fields for first and last name, email, and password, as well as cancel and submit buttons.

    Setup

    For the following, we’ll assume you're familiar with JavaScript and have Node installed on your PC. You don't need any prior React experience, and we’ll go over all of the essential ideas. A typical Node installation includes two command-line utilities, npm and npx.

    npm is used to install packages into a project, while npx is used to execute Node instructions from the command line. The advantage of npx is that the commands do not have to be installed on your machine. npx will first check to see if a command is installed in your current project folder.

    Run the following command in a terminal in a folder of your choice:

    npx create-react-app react-with-hooks

    This will create a new folder react-with-hooks and load it with a simple React app. You can now open the project in your preferred IDE. The main application component, App.js, is located in the project's src subdirectory.

    When you check within this file, you'll notice that it just has one function, App (). This function returns an element and defines the component using an extended JavaScript syntax known as JSX. You can use JSX to write HTML-style template syntax directly into your JavaScript file. The React toolchain is configured to transform this JavaScript/HTML hybrid into pure JavaScript that renders the HTML element.

    Make a new file in the src folder by the name of Search.js and paste the code below into it.

    import React from 'react';
    
    export function Search() { 
      return ( 
        <div> 
          <div className="search-input"> 
            <input type="text" placeholder="Search"/> 
          </div> 
          <h1 className="h1">Search Result</h1> 
          <div className="books"> 
            <table> 
              <thead> 
                <tr> 
                  <th className="title-col">Title</th> 
                  <th className="author-col">Author</th> 
                  <th className="year-col">Publication Year</th> 
                </tr> 
              </thead> 
              <tbody></tbody> 
            </table> 
          </div> 
        </div> 
      ); 
    }

    This is all that is required to construct a component. Of course, it doesn't accomplish anything yet and only shows an empty table. However, the Search component is already available in the application. Reopen src/App.js and insert the following import at the top of the file.

    import { Search } from './Search';

    Remove the import of logo.svg and replace the contents of the returned value in the App() function with the code below.

    <div className="App">
      <header>
        Books  
      </header>
      <Search/>
    </div>

    The <Search/> element has been utilized as if it were an HTML element. The JSX syntax allows you to add components directly in your JavaScript code in this manner. You can execute the following command in your terminal to test your application right now.

    npm start

    This will compile the application and redirect your browser to http://localhost:3000. You may leave this command running while you work on your code, and it will keep updating the program and reloading the browser page every time you make a change and save it.

    Controlled vs. Uncontrolled Components

    A controlled component is bound to a value, and its adjustments will be handled in code by using event-based callbacks. Here, the input form variable is handled by the react itself rather than the DOM. In this case, the mutable state is maintained in the state property and modified using setState().

    Controlled components have functions that regulate the data that occurs at each onChange event. This data is subsequently saved in the setState() method and updated. It helps components manage the elements and data of the form easier.

    The controlled component is a way you can handle the form input via the state. If you are using React Hooks, you can change the form input value by just one way and when the user begins writing some setState or useState characters, this state can be called and you can update it through one event like onChange. To kick-start your journey in web development, enroll in Online Courses in Web Development.  

    Example:

    import React, { useState } from "react";
    
    export default function App() { 
      const [inputValue, setInputValue] = useState(""); 
      const handleInputChange = (e) => { 
        setInputValue(e.target.value) 
      } 
      const handleSubmitButton = () => { 
        alert(inputValue); 
      }; 
      return ( 
        <div className="App"> 
          <input value={inputValue} onChange={handleInputChange} /> 
          <input type="submit" value="submit" onClick={handleSubmitButton} /> 
        </div> 
      ); 
    }

    The uncontrolled component is similar to standard HTML form inputs. The DOM handles the form data in this case. It keeps its own state and is updated when the input value changes. There is no need to construct an event handler for every state update when writing an uncontrolled component, and you may retrieve the form's value from the DOM using a ref.

    Example:

    import React, { useRef } from "react";
    
    export default function App() {
      const inputRef = useRef(null);
      const handleSubmitButton = () => {
        alert(inputRef.current.value);
      };
      return (
        <div className="App">
          <input type="text" ref={inputRef} />
          <input type="submit" value="submit" onClick={handleSubmitButton} />
        </div>
      );
    }

    Building the Form

    Forms are often defined within the <form> tag in both traditional HTML code and in ReactJS. It can have the typical form submission action that redirects to a new page, but this does not fully utilize rReact's capabilities; instead, as we all know, it is done using react components.

    As we all know, React is well-known for its components, hooks, and reusability. We will utilize a component to create a form. This form component, like any other HTML form, can include labels, input fields, a text area, a radio button, a check box, and so on. Furthermore, it can have alternative properties with minor changes, such as "for" being changed by "htmlfor" and "class" being replaced by "className." It can still have some of the traditional techniques, such as the "value" property.

    Example:

    Let us now expand our understanding of the useState hook by developing a user form that will accept name, email, and password as input. To handle submissions, it will feature a single submit button. We will also validate the fields; if any of the fields are empty, we will display an error message to the user; otherwise, we will display a success message.

    Step 1: Create a folder with any name of your choice and open the terminal and  Create react application using the following command:

    npx create-react-app signupform

    After running this command, the react application will be installed on your system and you will see a project structure. The src folder in the project contains various files like App.js and App.css, Now add a Form.js file in src folder and you will see the folder structure like this:

    Building a sign-up form using React
    Step 2: In the file, App.css paste the following code:

    .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;
    }

    Step 3: In the file, App.js paste the following code:

    import './App.css';
    import Form from "./Form"
    
    function App() {
    return (
    <div className="App">
    <Form />
    </div>
    
    );
    }
    
    export default App;

    Step 4: In the file, Form.js paste the following code:

    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>
    );
    }

    Step 5: Come into the signup form directory using the following command:

    cd signupform

    Step 6: Run the application using the command:

    npm start

    Building a sign-up form using React

    Looking to master Python fundamentals? Join our unique Python Fundamentals Course and unlock the power of this versatile language. Start coding like a pro today!

    Learnings in Form Building

    You can see that we have some client-side validation in place if you attempt a few samples. Remember that we made each input mandatory. As a result, if we leave any field blank, we will receive a warning. We also added a type to our email input, so it now checks to see if the email input is actually an email.

    When we submit the form, the data will display in the console.

    Thank you for your time! I hope you found this information useful in designing your own signup forms. If you have any questions, mention those in your comments and we’ll be happy to get you the answers.

    Profile

    Abhresh Sugandhi

    Author

    Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon