DEV Community

Cover image for Forms In React | Day 13
Jayant
Jayant

Posted on

Forms In React | Day 13

What

Forms → They are used to take in the user Input.

Goals :

  • Build Form with React
  • Understanding What Controlled Component are

React Forms

  • So in the HTML forms , they have their own state , the whole Application doesn’t know about the Form’s Data until we hit Submit.

So they are Called the Un-controlled Component , Where Site can’t access the form data.

React State

When our app has access to the form Data they are called the Controlled-Component.

Component

In the case of HTML the Form has it own State and it changes based on the User-Input.

But in React , We keep all our mutable data in the State and set it using the setState.

So how do we Control the React State ??

So we keep all our mutable data in the State , So what we can do is to store the User-input in the State.

Let’s have a look on this Example 👇

import React, { useState } from "react";

function ControlledForm() {
  const [Text, setText] = useState("Enter Your Name");

  const handleSubmit = (evt) => {
    evt.preventDefault();
    alert(`The value u Entered is ${Text}`);
  };
  const handleChange = (evt) => {
    setText(evt.target.value);
    console.log(Text); //It is a Asynchronomus process so it will take some time.
  };

  return (
    <div>
      <h1>Controlled Form</h1>
      <form>
        <input onChange={handleChange} value={Text} />
        <button onClick={handleSubmit}>Submit</button>
      </form>
    </div>
  );
}

export default ControlledForm;
Enter fullscreen mode Exit fullscreen mode

Try This on CodeSandBox

  • So in the Input tag we have set the value attribute to be Text (which is a State).
  • The Function handleChange runs on every keystroke to update the React state, the displayed value will update as the user types.
  • With a controlled component, every state mutation will have an associated handler function. This makes it easy to modify or validate user input.

The HandleClick Method →

const handleClick = (evt)=>{
    setText(evt.target.value);
    console.log("Updated!!!");
}
Enter fullscreen mode Exit fullscreen mode

Handling Multiple Events →

What if we want to use multiple input tag , Do we have make new onChange event Handler for Everyone??

  • The answer is NO!

ES2015

Property name

  • So we can Compute a Property in the Object also using the square-brakets []

Like this 👇

React

  • So Instead of making separate onChange handler for every single input , we can make some generic function.

React

  • To do so first we have include the name attribute to the input tag , and the name should match to the one we have declared in the state.
  • And in the handleChange function we have to use the square braces to make changes in the right place.

React Forms

React Forms

import React, { useState } from "react";

function MultiInputForm() {
  // const [Text, setText] = useState("");
  //We have defined a Object.
  const [Text, setText] = useState({ Name:"", Email:"", Number: "" });

  const handleSubmit = (evt) => {
    evt.preventDefault();
    alert(`The value u Entered is ${Text.Name} ${Text.Email}`);
  };
  const handleChange = (evt) => {
    // In this we are restoring the res ones and only changing the requierd ones.
    setText({ ...Text, [evt.target.name]: evt.target.value });
    // console.log(Text); //It is a Asynchronomus process so it will take some time.
  };

  return (
    <div>
      <h1>Multiple Input Form</h1>
      <form>
        {/* Be carful while setting the name it should be same as that u have entered in the state */}
        <input onChange={handleChange} value={Text.Name} name="Name" />
        <input
          onChange={handleChange}
          type="email"
          placeholder="Enter Email"
          name="Email"
        />
        <input
          onChange={handleChange}
          type="number"
          placeholder="Enter Mobile Number"
          name="Number"
        />

        <button onClick={handleSubmit}>Submit</button>
      </form>
    </div>
  );
}

export default MultiInputForm;
Enter fullscreen mode Exit fullscreen mode

Controlled Form

The HTML For

When ever u are using the label use htmlFor instead of for.

Cuz for is a Reserved word in the javaScript same with the instead we should use the className cuz class is also a Reserved keyword.

Passing Data to Parent Component

Passing Data To Parent

  • So Forms are generally Stateful so there should be a way to pass the state to the parent Component.

So we make a Form Component and changes it’s state using handleChange Function and after on submit we have an handleSubmit function which then call the Function which we passed as props and send the state as an argument and

then in parent Component we get that state and update the changes.

Shopping List Example

Shopping List

Keys and UUID

Keys and UUID

Happy Coding ☺️

Top comments (1)

Collapse
 
jay818 profile image
Jayant

Day 13 Completed 🎉