How To Create A Basic Form Using React Hooks.

How To Create A Basic Form Using React Hooks.

Table of contents

No heading

No headings in the article.

Forms are very important web components in React Js and Web development in general. This is because they provide a medium by which user data and information are collected, thereby enhancing user interaction in a website.

Forms in React Js are very identical to forms in plain HTML. However, the concept of build is a little different.

Just like in regular HTML, forms have a default behavior of browsing to a new page when they are submitted. This is also the default outcome in React. However, React offers a more convenient, stateful and reactive approach to create forms. This approach requires making use of “controlled components”, and it involves handling form submissions with Javascript functions.

please NOTE that the entire codebase for this lesson is found at the end of the document.

CONTROLLED COMPONENTS: In traditional HTML, form elements like

<input>

and

<select>

manage their state independently (through the DOM) but in React, authority to manage state is transferred from the form elements to React’s components. Then, form data is stored in React’s state and updated with the setState() method thereby making React’s state to be the “single source of truth”. In React, the aim is to modify state based on the actions of the user on the form. In regular HTML, form details are collected upon user submission but in React, user interaction with form elements cause the state to re-render and update itself.. To achieve this, the components have functions that manage the data which is passed into them on every Change event.

import React,{useState} from "react";

export default function App(){

    const [formData,setFormData] = 
    React.useState({firstName:"",
     email:"",
     comments:"", 
     isFriendly:true,
     favColor:"" 
    })

function handleChange(event){
    const{name,value,type,checked} = event.target;
    console.log(event)
    setFormData(prevFormData=>{
        return{
            ...prevFormData,
            [name]: type === "checkbox" ? checked : value
        }
    })
}


return(
    <form onSubmit={handleSubmit}>
        <label htmlFor="firstName"> firstName</label>
        <input
            id="firstName"
            type="text"
            name="firstName"
            value={formData.firstName}
            onChange={handleChange}
        />

MANAGING MULTIPLE INPUTS IN CONTROLLED ELEMENTS:

To handle multiple controlled input elements;

  • Add a name attribute to each element just as shown below and initialize your state with the names of your input elements, but the values should be empty. This is because the values represent the state and if they are occupied, then your form will be defaultly rendered with text in its input fields.
//React state
// the values should be empty..
    const [formData,setFormData] = 
    React.useState({firstName:"",
     email:"",
     comments:"", 
     isFriendly:false,
     favColor:"" 
    })
          <label htmlFor="firstName"> firstName</label>
         <input
            id="firstName"
            type="text"
            **name="firstName"**
            value={formData.firstName}
            onChange={handleChange}
        />
        <br/>
        <label htmlFor="lastName"> lastName</label>
        <input
            id="lastName"
            type="email"
            **name="email"**
            value={formData.email}
            onChange={handleChange}
        />

.

  • In the event handler function, destructure event.target to obtain the name and value attributes.
function handleChange(event){
    **const{name,value,type,checked} = event.target;**
    console.log(event)
    setFormData(prevFormData=>{
        return{
            ...prevFormData,
            [name]: type === "checkbox" ? checked : value
        }
    })
}
  • Spread the values of the state into the setState() function.
function handleChange(event){
    **const{name,value,type,checked} = event.target;**
    console.log(event)
    setFormData(oldFormData=>{
        return{
            **...oldFormData, **
            [name]: type === "checkbox" ? checked : value
        }
    })
}
  • To update state, use square brackets around the property, name.
function handleChange(event){
    **const{name,value,type,checked} = event.target;**
    console.log(event)
    setFormData(prevFormData=>{
        return{
            ...prevFormData,
            *[name]*: type === "checkbox" ? checked : value
        }
    })
}
  • In your form elements, set a value attribute to be the value of the corresponding name in state.
  <input
            id="firstName"
            type="text"
            name="firstName"
            *value={formData.firstName}*
            onChange={handleChange}
        />

TEXTAREA:

Just like input tags, textareas in React make use of a value attribute to define their content. The name attribute must also be added to enable the handler function. It should match the name in state.

         <textarea
            id="comments"
            name="comments"
            value={formData.comments}
            onChange={handleChange}

           />

CHECKBOXES:

Checkboxes in react are just another form of input elements with a type of checkbox. They pass their values as booleans. Because of this, they don’t use a value attribute, rather they use a checked attribute which may either be true or false depending on user interaction. In React’s state, the checkbox's name attribute which collects the value is set to false as the default. To add a label to checkboxes, an id is added to the checkbox elements. In the handler function, the state property is modified to handle the checked type.

      <input
            type="checkbox"
            id="isFriendly"
            name="isFriendly"
            checked={formData.isFriendly}
            onChange={handleChange}
        />
//react state

 const [formData,setFormData] = 
    React.useState({firstName:"",
     email:"",
     comments:"", 
     *isFriendly:false,*
     favColor:"" 
    })

RADIO BUTTONS:

These are another set of input elements with a different type of radio. For radio buttons, the value of the name attribute remains the same irrespective of how many the input elements are. This makes it possible for a single option to be selected. However, they should have different values showing the options they represent. Radio buttons also use a checked attribute which compares the value of the element in state to their individual values to check when a specific one is selected.

<fieldset>
            <input
                type="radio"
                id="unemployed"
                name="employment"
                value="unemployed"
                checked={formData.employment==="unemployed"}
                onChange={handleChange}
            />

            <label htmlFor="unemployed"> Unemployed</label>

            <input
                type="radio"
                id="employed"
                name="employment"
                value="employed"
                checked={formData.employment==="employed"}
                onChange={handleChange}
            />

            <label htmlFor="employed"> Employed</label>


        </fieldset>
//React state
    const [formData,setFormData] = 
    React.useState({firstName:"",
     email:"",
     comments:"", 
     isFriendly:false,
     favColor:"" 
    })

SELECT TAG:

The select tag element carries:

  • An ID attribute, to connect with the label.
  • A value attribute which compares to the value in the state..
  • An event attribute
  • A name attribute, for identification.
<label htmlFor="favColor">What is your favourite color</label>

        <select id="favColor"
                value={formData.favColor}
                name="favColor"
                onChange={handleChange}>

            <option value=""> --Choose--</option>
            <option value="red"> green</option>
            <option value="red"> Purple</option>
            <option value="red"> Blue</option>
            <option value="red"> Pink</option>
        </select>

SUBMITTING A FORM

Forms in react are submitted using a submit button which must be put into the form body. Form buttons have a default type of submit. Clicking a form button will trigger a submit event which is handled by a submit handler function.

To prevent the form from submitting to a new page, database or URL, add

event.preventDefault();

into your submit handler function.

// submit handler function

    function handleSubmit(event){
        event.preventDefault();
        console.log(event);
    }
        <button>Submit</button>
    </form>

Here is the general codebase for this lesson:

import React,{useState} from "react";

export default function App(){
//React state
    const [formData,setFormData] = 
    React.useState({firstName:"",
     email:"",
     comments:"", 
     isFriendly:false,
     favColor:"" 
    })

//change event handler function
    function handleChange(event){
    const{name,value,type,checked} = event.target;
    console.log(event)
    setFormData(prevFormData=>{
        return{
            ...prevFormData,
            [name]: type === "checkbox" ? checked : value
        }
    })
}


// submit handler function
function handleSubmit(event){
    event.preventDefault();
    console.log(event);
}


return(
    <form onSubmit={handleSubmit}>
        <label htmlFor="firstName"> firstName</label>
        <input
            id="firstName"
            type="text"
            name="firstName"
            value={formData.firstName}
            onChange={handleChange}
        />
        <br/>
        <label htmlFor="lastName"> lastName</label>
        <input
            id="lastName"
            type="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
        />

        <br/>
        <label htmlFor="comments"> comments</label>
        <textarea
            id="comments"
            name="comments"
            value={formData.comments}
            onChange={handleChange}

        />

        <br/>
        <input
            type="checkbox"
            id="isFriendly"
            name="isFriendly"
            checked={formData.isFriendly}
            onChange={handleChange}
        />


        <br/>

        <fieldset>
            <input
                type="radio"
                id="unemployed"
                name="employment"
                value="unemployed"
                checked={formData.employment==="unemployed"}
                onChange={handleChange}
            />

            <label htmlFor="unemployed"> Unemployed</label>

            <input
                type="radio"
                id="employed"
                name="employment"
                value="employed"
                checked={formData.employment==="employed"}
                onChange={handleChange}
            />

            <label htmlFor="employed"> Employed</label>


        </fieldset>

        <br/>
        <label htmlFor="favColor">What is your favourite color</label>

        <select id="favColor"
                value={formData.favColor}
                name="favColor"
                onChange={handleChange}>

            <option value=""> --Choose--</option>
            <option value="red"> green</option>
            <option value="red"> Purple</option>
            <option value="red"> Blue</option>
            <option value="red"> Pink</option>
        </select>

        <button>Submit</button>

    </form>
    )


}

Hurray!!! You have successfully reached the end of this document. If you didn't find the frm element that you're looking for, you can visit the official blog of React Js React form, to learn more.

Thanks for reading. I hope you learnt a lot from this document. You can connect with me on twitter @hey_kachi to learn more about web development, tools and resources.