Learn how to work with forms and form elements such as checkboxes, textareas, and single-line text inputs.

For instance:

Above we have afirstNamestate, anonInputevent, and ahandleChangehandler.

ThehandleChangefunction runs on every keystroke to update thefirstNamestate.

A Mac laptop on a table alongside two external monitors.

For example:

TheformDatawill serve as the state variable to manage and update all input fields inside the form.

Ensure the names of the properties in the state object are identical to the input elements names.

The code block above used anonInputevent and a handler function,handleFirstNameChange.

ThishandleFirstNameChangefunction will update the state properties when called.

The values of the state properties will be the same as those of their corresponding input elements.

This behavior is inconvenient in some situations, like when you want tovalidate the data entered into a form.

This can be easily achieved in React using controlled components.

With React, the set state function modifies a dynamic state stored in the component’s state property.

you could combine the two states by making the React state the single source of truth.

This way, the component that creates a form controls what happens when a user enters data.

Input form elements with values that React controls are called controlled components or controlled inputs.

The value of the input is always determined by the state when using a controlled component.

Handling the Textarea Input Element

Thetextareaelement is like any regular input element but holds multi-line inputs.

It is useful when passing information that requires more than a single line.

This makes it work like a default React input element.

Working With Reacts Checkbox Input Element

Things are a little different when working withcheckboxinputs.

The input field of the typecheckboxdoes not have a value attribute.

However, it has acheckedattribute.

The label element refers to the ID of the input element using thehtmlForattribute.

Thecheckboxis better used as a controlled input.

This code block generates anisCheckedstate, and sets its initial value tofalse.

It sets the value ofisCheckedto thecheckedattribute in the input element.

ThehandleChangefunction will fire and change the state value ofisCheckedto its opposite whenever you tap on the checkbox.

If not, it assigns the values of thevalueattribute.