React apps have a form element, which is slightly different from the HTML form as it maintains its internal state for the values. This guide will cover two different approaches to setting values of input elements.
Form controls in React are a bit different from the standard HTML form controls because each input element in a React form manages the internal state behind the scene.
Using a controlled form input approach, you can maintain the state values as an input for the various form controls.
For that, you need to maintain a state like this:
1this.state = {
2 key1: "value1",
3 key2: "value2",
4 key3: "value3",
5};
Note that you can modify its default/initial values based on the functional requirement.
This next example shows shows how to use a controlled input approach.
1import React, { Component } from "react";
2
3class SimpleForm extends Component {
4 constructor() {
5 super();
6 this.state = {
7 };
8 this.onInputchange = this.onInputchange.bind(this);
9 this.onSubmitForm = this.onSubmitForm.bind(this);
10 }
11
12 onInputchange(event) {
13 this.setState({
14 [event.target.name]: event.target.value
15 });
16 }
17
18 onSubmitForm() {
19 console.log(this.state)
20 }
21
22 render() {
23 const { items } = this.state;
24
25 return (
26 <div>
27 <div>
28 <label>
29 First Name :
30 <input
31 name="fname"
32 type="text"
33 value={this.state.fname}
34 onChange={this.onInputchange}
35 />
36 </label>
37 </div>
38 <div>
39 <label>
40 Last Name :
41 <input
42 name="lname"
43 type="text"
44 value={this.state.lname}
45 onChange={this.onInputchange}
46 />
47 </label>
48 </div>
49 <div>
50 <label>
51 Email :
52 <input
53 name="email"
54 type="text"
55 value={this.state.email}
56 onChange={this.onInputchange}
57 />
58 </label>
59 </div>
60 <div>
61 <button onClick={this.onSubmitForm}>Submit</button>
62 </div>
63 </div>
64 );
65 }
66}
67
68export default SimpleForm;
In the above source code, you have one form with three different controls called first name
, last name
, and email
. Each form control is attached with one common event called this.onInputChange()
.
1onInputchange(event) {
2 this.setState({
3 [event.target.name]: event.target.value
4 });
5}
After getting values from the form control, it stores the value based on the name of key like this:
1[event.target.name]: event.target.value;
2
3i.e. fname : value
Any modifications the user makes to the the initial or an empty value are reflected in the state object of the components.
Once you submit the form, the state object should look like this:
1{
2 email: "[email protected]"
3 fname: "Test first name"
4 lname: "Test last name"
5}
This is how you can make use of controlled form inputs, which manage events for each element and store values to the state object of the components.
Now that you have learned the primary approach to work with the form inputs, you can try another approach called uncontrolled, which manages the form data using the DOM itself.
The uncontrolled component approach is the opposite of a controlled approach, where you can get access to the form control values using ref
.
Ref
is the way to get access to the different DOM elements created within the render()
section.
Below is the simple syntax of using the ref
.
1class TestComponent extends Component {
2 constructor(props) {
3 super(props);
4 // Declaring refs
5 this.myRef = React.createRef();
6 }
7 render() {
8 return <element ref={this.myRef} />;
9 }
10}
In the example, notice that there is only one statement that declares the ref
.
1this.myRef = React.createRef();
And after declaring the ref
, it gets access just like this:
1<element ref={this.myRef} />
Please refer to the complete working example below.
1import React, { Component } from "react";
2
3class RefExample extends Component {
4 constructor() {
5 super();
6 this.onSubmitForm = this.onSubmitForm.bind(this);
7 }
8
9 onSubmitForm() {
10 console.log(this.input.value);
11 }
12
13 render() {
14 return (
15 <div>
16 <div>
17 <label>
18 First Name :
19 <input
20 name="fname"
21 type="text"
22 ref={myinput => (this.input = myinput)}
23 />
24 </label>
25 </div>
26 <div>
27 <button onClick={this.onSubmitForm}>Submit</button>
28 </div>
29 </div>
30 );
31 }
32}
33
34export default RefExample;
Here in the above example, there is one form of control to accept the first name
from the user. In this approach, the additional props are added like this:
1ref={myinput => (this.input = myinput)}
It means that reference is assigned to the form control so its value can be accessed later on when it's needed.
1onSubmitForm() {
2 console.log(this.input.value);
3}
It is a different approach than the controlled components approach; thus, the uncontrolled components approach is not suitable because it keeps the source of truth within the DOM itself.
You can also manipulate the input and its behavior using the ref
values, for example, by focusing the input control shown below.
1onSubmitForm() {
2 console.log(this.input.focus());
3}
In the above source code, the ref
value is being used along with the function focus()
which focuses on the input element.
This is how you can make use of an uncontrolled approach when you don’t want to do too much work and want to create the form quickly.
The controlled and uncontrolled approaches are different ways to use the form elements to manipulate the form values in a React app. It's not necessary to use any specific approach while working with the form; it depends on how you want to structure your app.
Now you can try both approaches and make an informed decision on the one that works best for you. I hope this guide will help you get started with forms in React.
Explore these React courses from Pluralsight to continue learning: