Single state handles the form in React Js

HTML forms allow users to enter data into input fields that accept text, passwords, emails, numbers, colors, phone numbers, dates, and more. Once all inputs have been collected, the form can be submitted for further processing using the submit button.

React Form

HTML form elements maintain their own state. Updating this state property is only possible through the setState() method.

The React in-built hook, useState() makes it easier to manage.

Good programming practice is to treat React’s state as the only source of truth. A React component with a form inside must handle everything that happens to the form when its

 

React Form Code

import { useEffect, useState } from "react";

import "./styles.css";




export default function App() {

  const [state, setState] = useState({

    firstName: "",

    lastName: "",

    email: "",

    password: "",

    address: "",

    checkMe: false,

    state: ""

  });

  const handleChange = (evt) => {

    const name = evt.target.name;

    const value =

      evt.target.type === "checkbox" ? evt.target.checked :                   evt.target.value;

    setState((prevState) => ({ ...prevState, [name]: value }));

  };

  useEffect(() => {

    console.log(state);

  }, [state]);




  return (

    <>

      <div>

        <label>Full Name</label>

        <input

          type="text"

          name="firstName"

          value={state.firstName}

          onChange= {handleChange}

        />

      </div>

      <div>

        <label>Last Name</label>

        <input

          type="text"

          name="lastName"

          value={state.lastName}

          onChange={handleChange}

        />

      </div>

      <div>

        <label>Email</label>

        <input

          type="text"

          name="email"

          value={state.email}

          onChange={handleChange}

        />

      </div>

      <div>

        <label>Password</label>

        <input

          type="password"

          name="password"

          value={state.password}

          onChange={handleChange}

        />

      </div>

      <div>

        <label>State</label>

        <select name="state" onChange={handleChange} value={state.state}>

          <option>jaunpur</option>

          <option>Allahabad</option>

          <option>Prayagraj</option>

        </select>

      </div>

      <div>

        <label>Address</label>

        <input

          type="text"

          name="address"

          value={state.address}

          onChange={handleChange}

        />

      </div>

      <div>

        <label>Check Me</label>

        <input

          type="checkbox"

          name="checkMe"

          value={state.checkMe}

          onChange={handleChange}

        />

      </div>

    </>

  );

}

Leave a Reply