January 28, 2023

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

How to use React forms in JSX? Example Tutorial


Forms are an essential part of web application development. You can find forms on almost every website you visit. Forms are important because they are used to handle input from the users. Websites will not function properly if there is no way for input handling. 

Input can be taken in various forms. The most common type of input is text input. Other forms of input are checkboxes, radio buttons, and ranges. 

In React, forms are created like they are created in HTML. The most important part of forms in React is handling them. In this article, we will discuss how to create forms in React and handle them. 


React forms

In React, we have to create forms in JSX which are more or less similar to HTML forms. After that, we will use the event handlers and React state to handle the inputs.

Creating a form in JSX.

Observe the following code.

export default function App() {

  return (

    <div className=“App”>

      <h2> Register here! </h2>

      <form>

        <label>

          {” “}

          Name: <input type=“text” />

        </label>

        <label>

          {” “}

          Email: <input type=“email” />

        </label>

        <br />

        <br />

        <label>

          {” “}

          Password: <input type=“password” />

        </label>

        <br /> <br />

        <label>

          Gender: <input type=“radio” value=“male” /> Male{” “}

          <input type=“radio” value=“female” /> Female

        </label>

        <br />

        <br />

        <button type=“submit”>Submit</button>

      </form>

    </div>

  );

}

In the above code, a basic form is created using the <form> tag. The form contains three input fields and a button. 

If the button is clicked, the page will reload because the button has “submit” as its type. To avoid this, we need to create a submit handler.

const submitHandler = (e) => {

  e.preventDefault();

};

e.preventDefault will prevent the page from default reloading. To make it work, we need to assign this handler to the form’s onSubmit event.

<form onSubmit={submitHandler}></form>

Collecting data using state

To collect data from each input field, we have to create a state for each of them. Let’s use the useState react hook to define the states. 

const [name, setName] = useState(“”);

const [email, setEmail] = useState(“”);

const [password, setPassword] = useState(“”);

const [gender, setGender] = useState(“”);

Next, we need to set the value for every input like this.

<label>

  {” “}

  Name: <input type=“text” value={name} />

</label>;

Similarly, the value should be defined according to the state. 

Finally, we need to use the onChange event to handle the value entered by the user. 

<label>

  {” “}

  Name:{” “}

  <input type=“text” value={name} onChange={(e) => setName(e.target.value)} />

</label>;

When the user enters a value in the name input field, that value is assigned to the “name” state. Similarly, an onChange event should be assigned to every input field. 

The data will be submitted when the submit button is clicked. Let’s update the submit handler to display the form data in the console.

const submitHandler = (e) => {

  e.preventDefault();

  console.log(

    `Name: ${name}n

   Email: ${email}n

   Password: ${password}n

   Gender: ${gender}`

  );

};

This is how the entire component looks.

import { useState } from “react”;

import “./styles.css”;

 

export default function App() {

  const [name, setName] = useState(“”);

  const [email, setEmail] = useState(“”);

  const [password, setPassword] = useState(“”);

  const [gender, setGender] = useState(“”);

 

  const submitHandler = (e) => {

    e.preventDefault();

    console.log(

      `Name: ${name}nEmail: ${email}nPassword: ${password}nGender: ${gender}`

    );

  };

 

  return (

    <div className=“App”>

      <h2> Register here! </h2>

      <form onSubmit={submitHandler}>

        <label>

          {” “}

          Name:{” “}

          <input

            type=“text”

            value={name}

            onChange={(e) => setName(e.target.value)}

          />

        </label>

        <label>

          {” “}

          Email:{” “}

          <input

            type=“email”

            value={email}

            onChange={(e) => setEmail(e.target.value)}

          />

        </label>

        <br />

        <br />

        <label>

          {” “}

          Password:{” “}

          <input

            type=“password”

            value={password}

            onChange={(e) => setPassword(e.target.value)}

          />

        </label>

        <br /> <br />

        <label>

          <div onChange={(e) => setGender(e.target.value)}>

            Gender: <input type=“radio” value=“male” /> Male{” “}

            <input type=“radio” value=“female” /> Female

          </div>

        </label>

        <br />

        <br />

        <button type=“submit”>Submit</button>

      </form>

    </div>

  );

}

Let’s test the form by entering the values.

The form data will be displayed in the console when the submit button is clicked.

Wrapping it up

Working with the form can be complicated if the basics are not clear. But it is very important to understand the forms in React because you will definitely encounter them. Forms in React are quite similar to the forms in HTML.

The most important part is handling the input. With the introduction of React hooks, it is easy to handle the form inputs. In this article, we created a basic form in React and used the useState hook to handle the input values. 



Source link