How to use form in React js

In this article I am going to show how can use form in react using react hook

Very first you need to import react hook useState from react

 

Example:

import { useState } from "react";

Now you need to use useState hook inside your components.

Inside of useSate hook you can define a JavaScript object with some property

Like bellow

 const [user, setUser] = useState({
    name: String,
    email: String,
    password: String,
  });

 

Now you can use this hook in your from like this

 <form onSubmit={handleSubmit}>

        <input

          type="text"
          required
          placeholder="Type your name"

          onChange={(e) => setUser({ ...user, name: e.target.value })}

        >
        </input>

        <input

          type="email"
          required
          placeholder="Type your email"

          onChange={(e) => setUser({ ...user, email: e.target.value })}

        >
        </input>
        <input

          type="password"
          required
          placeholder="Type your password"

          onChange={(e) => setUser({ ...user, password: e.target.value })}

        >
        </input>

        <button type="submit">Submit</button>

      </form>

 

Create a function named handleSubmit or what are you like

  const handleSubmit = (e) => {

    e.preventDefault();
    e.target.reset();

    try {
      //call API from here
    } catch (error) {
      console.log(error.message);

    }
  };

 

Complete Example

import React, { useState } from "react";

export default function App() {

  const [user, setUser] = useState({
    name: String,
    email: String,
    password: String,
  });

  const handleSubmit = (e) => {

    e.preventDefault();
    e.target.reset();

    try {
      //call API from here
    } catch (error) {
      console.log(error.message);
    }

  };

  return (
    <>

      <form onSubmit={handleSubmit}>
        <input

          type="text"
          required
          placeholder="Type your name"

          onChange={(e) => setUser({ ...user, name: e.target.value })}
        >
        </input>

        <input

          type="email"
          required
          placeholder="Type your email"

          onChange={(e) => setUser({ ...user, email: e.target.value })}
        >
        </input>

        <input

          type="password"
          required
          placeholder="Type your password"

          onChange={(e) => setUser({ ...user, password: e.target.value })}
        >
        </input>

        <button type="submit">Submit</button>

      </form>

    </>
  );
}

 

About Author

Photo

Hi, I am Mahbub Hasan
Software Engineer

I am very much interested to share my programming
and development knowledge with the people.I will try
to update my blog everyday with new technology inshallah.

Thank You

For Visiting My Blog.

Contact Me