Author -  Sai gowtham

Handling Forms in React using Hooks

In this tutorial, we are going to learn about how to handle the forms in react apps by using hooks.

Forms

Forms allow us to accept the data from the users and sent to the server for processing. They are a different type of forms such as Login, Register and Contact, etc.

In HTML5 we have form elements like input,textarea, select they maintain there own internal state in the dom but in react we maintain the form elements state inside the component so that we can have full control over the form elements.

What is Form handling

Form handling means how we handle the form data when a user changes the value or submits the form.

Let’s see an example of how we handle the input element data with react hooks.

import React,{useState} from 'react';

function Form(){

 const [name,setName] = useState('');
 function handleNameChange(e){      setName(e.targe.value) }
 function handleSubmit(e){
   e.preventDefault() // stops default reloading behaviour
     console.log(name); }

    return (
        <form onSubmit={handleSubmit}>
          <input placeholder="Name" value={name}           onChange={handleNameChange}/>          <button>Submit</button>
       </form>
    )
}

In the above code, we have set the value attribute of an input element to name property and onChange event handler method handleNameChange runs on every time we enter some data in the input element,and it updates the name property by using setName method, so that we keep sync the value with react state (name property).

handleSubmit method is used to submit the form.

select element

<select> element helps us to create a drop-down list, let’s see an example of how to create a drop-down list and handle the data.

import React,{useState} from 'react';

function FormSelect() {
    //initial value set to react
 const [framework,setFramework] = useState('react');
 function handleChange(e){    setFramework(e.target.value); };
  function handleSubmit(e){
    e.preventDefault();
    console.log(framework);
  };

    return (
      <form onSubmit={handleSubmit}>
        <h2>Choose your framework</h2>
        <select onChange={handleChange} value={framework}>          <option value="react">React</option>
          <option value="angular">Angular</option>
          <option value="vue">Vue</option>
        </select>
        <button type="submit">Submit</button>
      </form>
    );
}

Here we created a dropdown list of frameworks in <select> element we set value attribute to framework property and onChange event handler is added.

The nested <option> elements contain a value attribute which is holding the data so that whenever we select a particular option handleChange method is invoked and changes the framework property value with the <option> attribute value.

select-element-react-hooks

Have you seen the select element also follows the similar pattern like input element so that why can’t we create a custom react hook and reuse it on every form element?

Creating custom hooks

import React,{useState} from 'react';

function useInput(initialValue){
   const [value,setValue] = useState(initialValue);
    function handleChange(e){        setValue(e.target.value);    }
   return [value,handleChange];
}

Here we created a custom hook called useInput let’s use it now.

Using custom useInput() hook

function LoginForm(){

const [email,setEmail] = useInput('');const [password,setPassword] = useInput('');
function handleSubmit(e){
    e.preventDefault();
    console.log(email,password)
}

   return(
       <form onSubmit={handleSubmit}>
          <input placeholder="Email" type="email"
           value={email} onChange={setEmail}/>           <input placeholder="password" type="password"
           value={password} onChange={setPassword}/>          <button>Submit</button>
       </form>
   )
}

Now our LoginForm component looks much cleaner by using a useInput() custom hook.

login-form-custom-hooks

similarly we can use our useInput hook with other form elements.

Radio buttons example

function RadioButtons() {
  const [data] = useState({male:"male",female:"female",other:"other"})
  const [gender, setGender] = useInput("");  function handleSubmit(e) {
    e.preventDefault();
    console.log(gender);
  }

return (
 <form onSubmit={handleSubmit}>
    <h1>Select Your Gender</h1>
      <div>
        <input type="radio" id={data.male} value={data.male}        checked={data.male === gender} onChange={setGender}/>        <label htmlFor={data.male}>Male</label>      </div>
      <div>
        <input type="radio" id={data.female} value={data.female}        checked={data.female === gender} onChange={setGender}/>        <label htmlFor={data.female}>Female</label>       </div>
       <div>
        <input type="radio" id={data.other}  value={data.other}        checked={data.other === gender} onChange={setGender}/>        <label htmlFor={data.other}>Other</label>       </div>
     <button>submit</button>
  </form>
  )
}

Textarea element example

function Comments(){
  const [comment,setComment] = useInput(""); function handleSubmit(e) {
    e.preventDefault();
    console.log(comment);
  }
  return(
      <form onSubmit={handleSubmit}>
         <texarea value={comment} onChange={setComment}/>         <button>submit</button>
      </form>
  )
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY