React Form Handling - Input, Select, Check Box, and Radio Button

In this tutorial, we will learn React form handling with different input field types (Input, Select, Check Box, and Radio Button).

Example of a React form with an input element

This example demonstrates a basic form input element in React, where the value entered by the user is stored in state and can be accessed and processed further as needed.
import React, { useState } from 'react';

function FormExample() {
  const [name, setName] = useState('');
  
  const handleChange = (e) => {
    setName(e.target.value);
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Submitted name:', name);
  };
  
  return (
    <div>
      <h2>React Form Example</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="nameInput">Name:</label>
        <input 
          type="text" 
          id="nameInput" 
          value={name} 
          onChange={handleChange} 
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default FormExample;
In this example, we have a functional component called FormExample that represents a form with an input element for capturing a name. The useState hook is used to create a state variable called name and a corresponding setter function setName to manage the value of the input.

The handleChange function is triggered whenever the value of the input changes. It updates the name state with the new value entered by the user. 

The handleSubmit function is called when the form is submitted. It prevents the default form submission behavior and logs the submitted name to the console. The input element is controlled by the value attribute, which is set to the name state. 

The onChange event handler is attached to the input to capture any changes made by the user and update the state accordingly. When the form is submitted, the handleSubmit function is called, and the submitted name is logged into the console

Example of a React form with radio buttons

This example demonstrates a basic form with radio buttons in React, where the selected value is stored in state and can be accessed and processed further as needed.
import React, { useState } from 'react';

function FormExample() {
  const [gender, setGender] = useState('');

  const handleGenderChange = (e) => {
    setGender(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Selected gender:', gender);
  };

  return (
    <div>
      <h2>React Form Example</h2>
      <form onSubmit={handleSubmit}>
        <label>
          <input
            type="radio"
            name="gender"
            value="male"
            checked={gender === 'male'}
            onChange={handleGenderChange}
          />
          Male
        </label>
        <label>
          <input
            type="radio"
            name="gender"
            value="female"
            checked={gender === 'female'}
            onChange={handleGenderChange}
          />
          Female
        </label>
        <label>
          <input
            type="radio"
            name="gender"
            value="other"
            checked={gender === 'other'}
            onChange={handleGenderChange}
          />
          Other
        </label>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default FormExample;
In this example, we have a functional component called FormExample that represents a form with radio buttons for selecting a gender. The useState hook is used to create a state variable called gender and a corresponding setter function setGender to manage the selected gender value.

The handleGenderChange function is triggered whenever a radio button is clicked. It updates the gender state with the value of the selected radio button. 

The handleSubmit function is called when the form is submitted. It prevents the default form submission behavior and logs the selected gender to the console. Each radio button has a unique value attribute and shares the same name attribute. The checked attribute is set based on whether the gender state matches the respective radio button's value. The onChange event handler is attached to each radio button to capture the selection and update the state accordingly. 

When the form is submitted, the handleSubmit function is called, and the selected gender is logged into the console.

Example of a React form with checkboxes

This example demonstrates a basic form with checkboxes in React, where the selected values are stored in state and can be accessed and processed further as needed.
import React, { useState } from 'react';

function FormExample() {
  const [hobbies, setHobbies] = useState([]);

  const handleCheckboxChange = (e) => {
    const value = e.target.value;
    if (e.target.checked) {
      setHobbies([...hobbies, value]);
    } else {
      setHobbies(hobbies.filter((hobby) => hobby !== value));
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Selected hobbies:', hobbies);
  };

  return (
    <div>
      <h2>React Form Example</h2>
      <form onSubmit={handleSubmit}>
        <label>
          <input
            type="checkbox"
            value="reading"
            checked={hobbies.includes('reading')}
            onChange={handleCheckboxChange}
          />
          Reading
        </label>
        <label>
          <input
            type="checkbox"
            value="sports"
            checked={hobbies.includes('sports')}
            onChange={handleCheckboxChange}
          />
          Sports
        </label>
        <label>
          <input
            type="checkbox"
            value="cooking"
            checked={hobbies.includes('cooking')}
            onChange={handleCheckboxChange}
          />
          Cooking
        </label>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default FormExample;
In this example, we have a functional component called FormExample that represents a form with checkboxes for selecting hobbies. The useState hook is used to create a state variable called hobbies and a corresponding setter function setHobbies to manage the selected hobbies. 

The handleCheckboxChange function is triggered whenever a checkbox is clicked. It updates the hobbies state by adding or removing the value of the clicked checkbox based on its checked status. 

The handleSubmit function is called when the form is submitted. It prevents the default form submission behavior and logs the selected hobbies to the console. Each checkbox has a unique value attribute. The checked attribute is set based on whether the hobbies state includes the respective checkbox value. The onChange event handler is attached to each checkbox to capture the selection and update the state accordingly. 

When the form is submitted, the handleSubmit function is called, and the selected hobbies are logged into the console.

Example of a React form with a select dropdown

This example demonstrates a basic form with a select dropdown in React, where the selected value is stored in state and can be accessed and processed further as needed.
import React, { useState } from 'react';

function FormExample() {
  const [country, setCountry] = useState('');

  const handleCountryChange = (e) => {
    setCountry(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Selected country:', country);
  };

  return (
    <div>
      <h2>React Form Example</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="countrySelect">Select Country:</label>
        <select
          id="countrySelect"
          value={country}
          onChange={handleCountryChange}
        >
          <option value="">-- Select --</option>
          <option value="usa">USA</option>
          <option value="canada">Canada</option>
          <option value="uk">UK</option>
          <option value="australia">Australia</option>
        </select>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default FormExample;
In this example, we have a functional component called FormExample that represents a form with a select dropdown for selecting a country. The useState hook is used to create a state variable called country and a corresponding setter function setCountry to manage the selected country value. 

The handleCountryChange function is triggered whenever the value of the select dropdown changes. It updates the country state with the newly selected value. 

The handleSubmit function is called when the form is submitted. It prevents the default form submission behavior and logs the selected country to the console. The select dropdown is controlled by the value attribute, which is set to the country state. The onChange event handler is attached to the select element to capture any changes made by the user and update the state accordingly. 

When the form is submitted, the handleSubmit function is called, and the selected country is logged into the console.

Complete React Form Handling Example

Let's put together all the form input field types in a single functional component and test it:
import React, { useState } from 'react';

function FormExample() {
  const [name, setName] = useState('');
  const [gender, setGender] = useState('');
  const [hobbies, setHobbies] = useState([]);
  const [country, setCountry] = useState('');

  const handleGenderChange = (e) => {
    setGender(e.target.value);
  };
  
  const handleCountryChange = (e) => {
    setCountry(e.target.value);
  };

  const handleChange = (e) => {
    setName(e.target.value);
  };
  
  const handleCheckboxChange = (e) => {
    const value = e.target.value;
    if (e.target.checked) {
      setHobbies([...hobbies, value]);
    } else {
      setHobbies(hobbies.filter((hobby) => hobby !== value));
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Submitted name:', name);
    console.log('Selected gender:', gender);
    console.log('Selected hobbies:', hobbies);
    console.log('Selected country:', country);
  };
  
  return (
    <div className='center'>
      <h2>React Form Example</h2>
      <form onSubmit={handleSubmit}>
        <div>
        <label htmlFor="nameInput">Name:</label>
        <input 
          type="text" 
          id="nameInput" 
          value={name} 
          onChange={handleChange} 
        />
       </div><br />
       <div>
        <label>
          <input
            type="radio"
            name="gender"
            value="male"
            checked={gender === 'male'}
            onChange={handleGenderChange}
          />
          Male
        </label>
        <label>
          <input
            type="radio"
            name="gender"
            value="female"
            checked={gender === 'female'}
            onChange={handleGenderChange}
          />
          Female
        </label>
        <label>
          <input
            type="radio"
            name="gender"
            value="other"
            checked={gender === 'other'}
            onChange={handleGenderChange}
          />
          Other
        </label>

        </div> <br />
        
        <div>
        <label>
          <input
            type="checkbox"
            value="reading"
            checked={hobbies.includes('reading')}
            onChange={handleCheckboxChange}
          />
          Reading
        </label>
        <label>
          <input
            type="checkbox"
            value="sports"
            checked={hobbies.includes('sports')}
            onChange={handleCheckboxChange}
          />
          Sports
        </label>
        <label>
          <input
            type="checkbox"
            value="cooking"
            checked={hobbies.includes('cooking')}
            onChange={handleCheckboxChange}
          />
          Cooking
        </label>

        </div>
        <br />
        <div>
        <label htmlFor="countrySelect">Select Country:</label>
        <select
          id="countrySelect"
          value={country}
          onChange={handleCountryChange}
        >
          <option value="">-- Select --</option>
          <option value="usa">USA</option>
          <option value="canada">Canada</option>
          <option value="uk">UK</option>
          <option value="australia">Australia</option>
        </select>
        </div>
        <br />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default FormExample;
Let's use the FormExample component in the App component:

import FormExample from './components/FormExample'
import './App.css';

function App() {

  return (
    <div>
       <FormExample />
    </div>
  )
}

export default App
Add the below CSS class to the App.css file to display the form at the center:
.center {
  width: 50%;
  margin: auto;
  margin-top: 50px;
  border: 2px solid;
  padding: 10px;
}
Run the React app to see the result in the browser:

Related Tutorials

Comments