React101: Forms

Forms are considered to be React’s weakness, difficult to use and understand. However, it can be made easy by using libraries.
The difference in writing forms in Vanilla javascript and React is that, in React, the state variable keeps into account all keystrokes made to enter the input.
As you noticed in the above example, React does not need a “submit” button like Vanilla Javascript does. The state variable keeps track of the input value. But what happens, if there are multiple form elements?
This way would lead to duplicate code: several state variables and event handlers. To avoid that, we create a form object as shown in the example below. There are some notes added to the ‘Form.js’ file
Controlled Inputs
React can also control what inputs get entered. In HTML, form elements such as <input>
, <textarea>
, and <select>
typically maintain their own state and update it based on user input.
In React, a mutable state is typically kept in the state property of components, and only updated with setState
. In our example above, we have two states being maintained by the input element itself and by the state variable. This is what is also called “uncontrolled forms”.
To make React state the “single source of truth”, will give the ability to React component to control what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
To make the form a controlled component, value
property is added to the form element as shown below:
const [formData, setFormData] = React.useState({firstName: "",
lastName: ""})
<input
type="text"
placeholder="First Name"
onChange={handleChange}
name="firstName"
value={formData.firstName}
/>
Forms in React: Textarea
In React textarea />
has been made a self-closing tag so that it emulates the same behavior like the input
element.
<textarea
placeholder="comments"
onChange={handleChange}
name="comments"
value ={formData.comments}
/>
Forms in React: Checkbox
Checkboxes have been different from all inputs we did above as checkboxes hold boolean values than text. So it cannot be a string text, it will be a checked property whether the user has checked or not. A boolean value in the form object.
<input
type="checkbox"
id="isFriendly"
checked={formData.isFriendly}
/>
<label htmlFor="isFriendly">Are you friendly?</label>
The updated code-sandbox code is as below. A ternary operator is implemented to choose between checked or value options.
Forms in React: Radio Buttons
In React, Radio Buttons are a combination of checkboxes and text . The name
property is given the same value in all options because there is one variable that will be updated. The user can select only one value out of the given options, which is determined by value
property.
<fieldset>
<legend>Current employment status</legend>
<input
type="radio"
id="unemployed"
name="employment"
value="unemployed"
/>
<label htmlFor="unemployed">Unemployed</label>
<br />
<input
type="radio"
id="part-time"
name="employment"
value="part-time"
/>
<label htmlFor="part-time">Part-time</label>
<br />
<input
type="radio"
id="full-time"
name="employment"
value="full-time"
/>
<label htmlFor="full-time">Full-time</label>
<br />
</fieldset>
Radio-Buttons are controlled in a different way than checkboxes. The updated code in Sandbox explains it.
Forms: Select & Option
In React, the select
and option
are handled as below. The name
and value
properties are important to have controlled forms in React.
<select
id="favColor"
value={formData.favColor}
onChange={handleChange}
name="favColor"
>
<option value="">-- Choose --</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
Submitting the Form
In React submitting the form is easy in comparison to what we do in HTML. As all the data is captured in the state variable, we can send the variable to an API
function handleSubmit(event) {
event.preventDefault() //prevents refresh of the page, so that we
//dont loose values
submitToApi(formData)
}
<form onSubmit={handleSubmit}>
<input ... />
<button>Submit</button>
</form>
Form Challenge
Are you up for the below challenge? :D Open the sandbox once you are done.
Requirements:
- Create a state variable to keep track of 4 state
- If the passwords match, console log ” successful signup” or not
- If the checkbox is checked, console log “thanks for signing up”