Forms In React | Day 13
Tags: react, javascript, webdev, beginners
Published: 2022-01-16 19:02:36

### What

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

**Goals :**

- Build Form with React
- Understanding What Controlled Component are

![React Forms](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqwddbmxvzit52pjh0qn.png)
 

- **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzrtidgyrha2slnkfcow.png)
 

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

![Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fz74umksmzwlosyjohc.png)
 

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 👇**

```jsx
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;
```

[Try This on CodeSandBox](https://codesandbox.io/s/controlled-form-gdchs?file=/src/ControlledForm.js:0-628)

- **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 →**

```jsx
const handleClick = (evt)=>{
	setText(evt.target.value);
	console.log("Updated!!!");
}
```

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1dmjctvnrfp2g6bf2pz2.png)
 

![Property name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdzb7ucdbtcpgxvoxv3h.png)


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

Like this 👇

![React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g83ea7ju6otlo92wc088.png)
 

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

![React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7h89lcui78g9zydglwb4.png)
 

- **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77129ms5rsjff1hdw5ur.png)
 

![React Forms](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hbd204vfxe6war7fq0x6.png)
 

```jsx
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;
```

[Controlled Form](https://codesandbox.io/s/controlled-form-gdchs?file=/src/MultiInputForm.js:0-1272)


### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ax8zi8whma8uxlx10dx.png)
 

- **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1uqh2k4wm3m1gmjk7j5t.png)
 

### Keys and UUID

![Keys and UUID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ztuow2u4ge7xzvyckmt.png)
 

**Happy Coding ☺️**