Lesson 4
Diving Into React.js: Learn How to Handle Forms and States
Introduction

Welcome to our lesson on handling forms in React.js. Forms, which are the backbone of user interaction and data collection in web applications, are treated uniquely in React.js. Our goal is to learn how to create forms, manage their state, and handle their submissions. This lesson is fun and interactive. We'll start with form elements in React.js, move on to the interaction between forms and state, and finally wrap up with form submissions. Are you ready to roll?

Getting to Know Form Elements in React

Forms in React.js consist of several elements that allow users to input data. We have three main form elements: input, textarea, select, and label.

  • input: This versatile element allows users to provide data input. Its appearance and behavior vary based on the type attribute. For instance, type="text" creates a simple text field, type="radio" generates a radio button, and type="checkbox" yields a checkbox. Others include type="password" for password input fields and type="submit" for submit buttons.

  • textarea: This element is a text-input area typically used for inputs that require more than one sentence.

  • select: This element generates a dropdown list of pre-defined options, encapsulated by option tags.

  • label: Specifies a label for the associated element. Enhances user experience by binding text to its associated form control, so clicking on the label selects the control.

Let's view an example of a simple form with a text input field and a submit input button.

JavaScript
1import { useState } from "react"; 2 3function SimpleForm() { 4 const [name, setName] = useState(""); 5 6 const handleNameChange = (event) => { 7 setName(event.target.value); 8 }; 9 10 return ( 11 <form> 12 <label> 13 Name: 14 <input type="text" value={name} onChange={handleNameChange} /> 15 </label> 16 <input type="submit" /> 17 </form> 18 ); 19} 20 21export default SimpleForm;

The handleNameChange function captures and updates the input value (name) every time you type into the text field.

Note that in JSX, void elements like input need closing with />.

Here is an example of using the select form element:

JavaScript
1import { useState } from "react"; 2 3function SimpleForm() { 4 const [country, setCountry] = useState(""); 5 6 const handleCountryChange = (event) => { 7 setCountry(event.target.value); 8 }; 9 10 return ( 11 <form> 12 <label> 13 Select your country: 14 <select value={country} onChange={handleCountryChange}> 15 <option value="">--Please choose an option--</option> 16 <option value="United States">United States</option> 17 <option value="United Kingdom">United Kingdom</option> 18 <option value="Australia">Australia</option> 19 { /* ... (more options) ... */ } 20 </select> 21 </label> 22 <input type="submit" value="Submit" /> 23 </form> 24 ); 25} 26 27export default SimpleForm;

In this example, handleCountryChange function sets the state to the selected country whenever a new country is chosen from the dropdown.

State Management in React Forms

A crucial part of handling forms in React.js involves managing state. Generally, the form field's state corresponds to the form element's value attribute. This arrangement allows for controlling the value of the form input through the state, making the React component the "source of truth" for the input element.

Components that follow this method are known as Controlled Components. These components update the state with every input field change event. In our first form, the input field value updates whenever a key is pressed:

JavaScript
1 // ... 2 const handleNameChange = (event) => { 3 setName(event.target.value); 4 }; 5 // ...
Handling Form Submissions

When submitting a form, by clicking or pressing enter on a submit type input or a button type input, the data from the form fields is typically sent to the server, and the web page is refreshed. We aim to prevent this standard page refresh. By overriding this default behavior with preventDefault(), we can keep the page static while submitting the form.

Here's how we can accomplish it:

JavaScript
1 // ... 2 const handleSubmit = (event) => { 3 event.preventDefault(); // prevents form submission from refreshing the page 4 alert(`The input field text is "${value}"`); 5 }; 6 // ...

This handleSubmit function is triggered by the onSubmit form event. It acts by preventing the page from refreshing and displays an alert with the text from the form input.

Lesson Summary and Practice

Well done! You've learned the basics of handling forms in React.js, including form elements, state management, and form submissions. Coming up are fun practice exercises that will solidify these learnings and make you more comfortable with form handling in React.js. Don't worry, these tasks are designed to be engaging and highly relevant to real-life examples. See you there!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.