Author avatar

Gaurav Singhal

How to Use React to Set the Value of an Input

Gaurav Singhal

  • May 12, 2020
  • 7 Min read
  • 561 Views
  • May 12, 2020
  • 7 Min read
  • 561 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

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.

Controlled Input Approach

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:

1
2
3
4
5
this.state = {
  key1: "value1",
  key2: "value2",
  key3: "value3",
};
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import React, { Component } from "react";

class SimpleForm extends Component {
  constructor() {
    super();
    this.state = {
    };
    this.onInputchange = this.onInputchange.bind(this);
    this.onSubmitForm = this.onSubmitForm.bind(this);
  }

  onInputchange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  onSubmitForm() {
    console.log(this.state)
  }

  render() {
    const { items } = this.state;

    return (
      <div>
        <div>
          <label>
            First Name :
            <input
              name="fname"
              type="text"
              value={this.state.fname}
              onChange={this.onInputchange}
            />
          </label>
        </div>
        <div>
          <label>
            Last Name :
            <input
              name="lname"
              type="text"
              value={this.state.lname}
              onChange={this.onInputchange}
            />
          </label>
        </div>
        <div>
          <label>
            Email :
            <input
              name="email"
              type="text"
              value={this.state.email}
              onChange={this.onInputchange}
            />
          </label>
        </div>
        <div>
            <button onClick={this.onSubmitForm}>Submit</button>
        </div>
      </div>
    );
  }
}

export default SimpleForm;
jsx

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().

1
2
3
4
5
onInputchange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
}
jsx

After getting values from the form control, it stores the value based on the name of key like this:

1
2
3
[event.target.name]: event.target.value;

i.e. fname : value
jsx

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
3
4
5
{
    email: "[email protected]"
    fname: "Test first name"
    lname: "Test last name"
}

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.

Uncontrolled Input Approach

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.

1
2
3
4
5
6
7
8
9
10
class TestComponent extends Component {
  constructor(props) {
    super(props);
    // Declaring refs
    this.myRef = React.createRef();
  }  
  render() {
    return <element ref={this.myRef} />;
  } 
}
jsx

In the example, notice that there is only one statement that declares the ref.

1
this.myRef = React.createRef();
jsx

And after declaring the ref, it gets access just like this:

1
<element ref={this.myRef} />
jsx

Please refer to the complete working example below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import React, { Component } from "react";

class RefExample extends Component {
  constructor() {
    super();
    this.onSubmitForm = this.onSubmitForm.bind(this);
  }

  onSubmitForm() {
    console.log(this.input.value);
  }

  render() {
    return (
      <div>
        <div>
          <label>
            First Name :
            <input
              name="fname"
              type="text"
              ref={myinput => (this.input = myinput)}
            />
          </label>
        </div>
        <div>
          <button onClick={this.onSubmitForm}>Submit</button>
        </div>
      </div>
    );
  }
}

export default RefExample;
jsx

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:

1
ref={myinput => (this.input = myinput)}
jsx

It means that reference is assigned to the form control so its value can be accessed later on when it's needed.

1
2
3
onSubmitForm() {
    console.log(this.input.value);
}
jsx

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.

1
2
3
onSubmitForm() {
    console.log(this.input.focus());
}
jsx

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.

Conclusion

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.

1