Introduction
In this chapter, we will explore how to work with forms in React. Forms are essential for collecting user input and handling it in a controlled manner. We will cover the basics of form handling, focusing on key form controls like input, checkbox, radio, and select elements. We will start with examples using class components and then cover the same using functional components.
Table of Contents
- Basics of React Forms
- Controlled Components
- Example: Input Field
- Handling Different Form Controls
- Example: Checkbox
- Example: Radio Buttons
- Example: Select Dropdown
- Using Class Components
- Example: Complete Form with Class Components
- Using Functional Components
- Example: Complete Form with Functional Components
- Key Features of React Forms
- Conclusion
Basics of React Forms
Forms in React are similar to forms in HTML, but they are controlled by React state. This means that the form data is managed by the React component rather than the DOM. This allows you to have full control over the form’s data and behavior.
Controlled Components
Controlled components are form elements whose value is controlled by the state of a React component. This means that the form element’s value is determined by the component’s state, and any changes to the form element will update the component’s state.
Example: Input Field
Let’s start with a basic example of an input field using a class component.
-
Create a New File for the Component: In the
srcdirectory, create a new file namedInputFieldClass.js. -
Define the Component: Add the following code to
InputFieldClass.jsto create a controlled input component:// InputFieldClass.js import React, { Component } from 'react'; class InputFieldClass extends Component { constructor(props) { super(props); this.state = { inputValue: '' }; } handleChange = (event) => { this.setState({ inputValue: event.target.value }); }; render() { return ( <div> <h1>Controlled Input</h1> <input type="text" value={this.state.inputValue} onChange={this.handleChange} /> <p>Current Value: {this.state.inputValue}</p> </div> ); } } export default InputFieldClass;Explanation:
- The
InputFieldClasscomponent usesthis.stateto manage the value of the input field. - The
handleChangemethod updates the state with the current value of the input field. - The
valueattribute of the input field is set tothis.state.inputValue, making it a controlled component.
- The
-
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theInputFieldClasscomponent:// App.js import React from 'react'; import InputFieldClass from './InputFieldClass'; function App() { return ( <div> <InputFieldClass /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a controlled input field that updates the displayed value as you type.
Handling Different Form Controls
Example: Checkbox
-
Create a New File for the Component: In the
srcdirectory, create a new file namedCheckboxClass.js. -
Define the Component: Add the following code to
CheckboxClass.jsto create a controlled checkbox component:// CheckboxClass.js import React, { Component } from 'react'; class CheckboxClass extends Component { constructor(props) { super(props); this.state = { isChecked: false }; } handleChange = (event) => { this.setState({ isChecked: event.target.checked }); }; render() { return ( <div> <h1>Controlled Checkbox</h1> <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.handleChange} /> Check me </label> <p>Checkbox is {this.state.isChecked ? 'checked' : 'unchecked'}</p> </div> ); } } export default CheckboxClass; -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theCheckboxClasscomponent:// App.js import React from 'react'; import CheckboxClass from './CheckboxClass'; function App() { return ( <div> <CheckboxClass /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a controlled checkbox that updates the displayed status as you check and uncheck it.
Example: Radio Buttons
-
Create a New File for the Component: In the
srcdirectory, create a new file namedRadioButtonsClass.js. -
Define the Component: Add the following code to
RadioButtonsClass.jsto create a controlled radio buttons component:// RadioButtonsClass.js import React, { Component } from 'react'; class RadioButtonsClass extends Component { constructor(props) { super(props); this.state = { selectedOption: 'option1' }; } handleChange = (event) => { this.setState({ selectedOption: event.target.value }); }; render() { return ( <div> <h1>Controlled Radio Buttons</h1> <label> <input type="radio" value="option1" checked={this.state.selectedOption === 'option1'} onChange={this.handleChange} /> Option 1 </label> <label> <input type="radio" value="option2" checked={this.state.selectedOption === 'option2'} onChange={this.handleChange} /> Option 2 </label> <p>Selected option: {this.state.selectedOption}</p> </div> ); } } export default RadioButtonsClass; -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theRadioButtonsClasscomponent:// App.js import React from 'react'; import RadioButtonsClass from './RadioButtonsClass'; function App() { return ( <div> <RadioButtonsClass /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see controlled radio buttons that update the displayed selected option as you change the selection.
Example: Select Dropdown
-
Create a New File for the Component: In the
srcdirectory, create a new file namedSelectDropdownClass.js. -
Define the Component: Add the following code to
SelectDropdownClass.jsto create a controlled select dropdown component:// SelectDropdownClass.js import React, { Component } from 'react'; class SelectDropdownClass extends Component { constructor(props) { super(props); this.state = { selectedValue: 'option1' }; } handleChange = (event) => { this.setState({ selectedValue: event.target.value }); }; render() { return ( <div> <h1>Controlled Select Dropdown</h1> <select value={this.state.selectedValue} onChange={this.handleChange}> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <p>Selected value: {this.state.selectedValue}</p> </div> ); } } export default SelectDropdownClass; -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theSelectDropdownClasscomponent:// App.js import React from 'react'; import SelectDropdownClass from './SelectDropdownClass'; function App() { return ( <div> <SelectDropdownClass /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a controlled select dropdown that updates the displayed selected value as you change the selection.
Using Class Components
Example: Complete Form with Class Components
-
Create a New File for the Component: In the
srcdirectory, create a new file namedCompleteFormClass.js. -
Define the Component: Add the following code to
CompleteFormClass.jsto create a complete form component that includes input, checkbox, radio buttons, and select dropdown elements:// CompleteFormClass.js import React, { Component } from 'react'; class CompleteFormClass extends Component { constructor(props) { super(props); this.state = { username: '', isSubscribed: false, gender: 'male', favoriteColor: 'red' }; } handleChange = (event) => { const { name, value, type, checked } = event.target; this.setState({ [name]: type === 'checkbox' ? checked : value }); }; handleSubmit = (event) => { event.preventDefault(); alert(`Form submitted with the following data: Username: ${this.state.username} Subscribed: ${this.state.isSubscribed} Gender: ${this.state.gender} Favorite Color: ${this.state.favoriteColor}`); }; render() { return ( <div> <h1>Complete Form</h1> <form onSubmit={this.handleSubmit}> <label> Username: <input type="text" name="username" value={this.state.username} onChange={this.handleChange} /> </label> <br /> <label> Subscribe to newsletter: <input type="checkbox" name="isSubscribed" checked={this.state.isSubscribed} onChange={this.handleChange} /> </label> <br /> <label> Gender: <input type="radio" name="gender" value="male" checked={this.state.gender === 'male'} onChange={this.handleChange} /> Male <input type="radio" name="gender" value="female" checked={this.state.gender === 'female'} onChange={this.handleChange} /> Female </label> <br /> <label> Favorite Color: <select name="favoriteColor" value={this.state.favoriteColor} onChange={this.handleChange} > <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> </select> </label> <br /> <button type="submit">Submit</button> </form> </div> ); } } export default CompleteFormClass; -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theCompleteFormClasscomponent:// App.js import React from 'react'; import CompleteFormClass from './CompleteFormClass'; function App() { return ( <div> <CompleteFormClass /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a complete form with input, checkbox, radio buttons, and select dropdown elements. When you submit the form, it will display an alert with the form data.
Using Functional Components
The useState hook is used to manage state in functional components. For form handling, you can use useState to create state variables for each form control and update them with event handlers.
Example: Complete Form with Functional Components
-
Create a New File for the Component: In the
srcdirectory, create a new file namedCompleteFormFunction.js. -
Define the Component: Add the following code to
CompleteFormFunction.jsto create a complete form component using functional components and hooks:// CompleteFormFunction.js import React, { useState } from 'react'; function CompleteFormFunction() { const [formData, setFormData] = useState({ username: '', isSubscribed: false, gender: 'male', favoriteColor: 'red' }); const handleChange = (event) => { const { name, value, type, checked } = event.target; setFormData((prevFormData) => ({ ...prevFormData, [name]: type === 'checkbox' ? checked : value })); }; const handleSubmit = (event) => { event.preventDefault(); alert(`Form submitted with the following data: Username: ${formData.username} Subscribed: ${formData.isSubscribed} Gender: ${formData.gender} Favorite Color: ${formData.favoriteColor}`); }; return ( <div> <h1>Complete Form</h1> <form onSubmit={handleSubmit}> <label> Username: <input type="text" name="username" value={formData.username} onChange={handleChange} /> </label> <br /> <label> Subscribe to newsletter: <input type="checkbox" name="isSubscribed" checked={formData.isSubscribed} onChange={handleChange} /> </label> <br /> <label> Gender: <input type="radio" name="gender" value="male" checked={formData.gender === 'male'} onChange={handleChange} /> Male <input type="radio" name="gender" value="female" checked={formData.gender === 'female'} onChange={handleChange} /> Female </label> <br /> <label> Favorite Color: <select name="favoriteColor" value={formData.favoriteColor} onChange={handleChange} > <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> </select> </label> <br /> <button type="submit">Submit</button> </form> </div> ); } export default CompleteFormFunction; -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theCompleteFormFunctioncomponent:// App.js import React from 'react'; import CompleteFormFunction from './CompleteFormFunction'; function App() { return ( <div> <CompleteFormFunction /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a complete form with input, checkbox, radio buttons, and select dropdown elements. When you submit the form, it will display an alert with the form data.
Key Features of React Forms
- Controlled Components: Forms in React are controlled by state, allowing you to manage the form data and behavior fully.
- Multiple Form Controls: React supports various form controls, including input fields, checkboxes, radio buttons, and select dropdowns.
- Event Handling: React provides straightforward event handling for form submission and input changes.
- Flexibility: Forms can be managed using both class components and functional components with hooks.
Conclusion
In this chapter, you learned how to work with forms in React, including handling different form controls like input fields, checkboxes, radio buttons, and select dropdowns. You also learned how to create complete forms using both class components and functional components with hooks. Understanding how to manage forms is essential for collecting and handling user input effectively in React applications. In the next chapter, we will explore more on how to work with forms in React using Functional Components.