Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Use React to Set the Value of an Input

May 12, 2020 • 7 Minute Read

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:

      this.state = {
  key1: "value1",
  key2: "value2",
  key3: "value3",
};
    

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.

      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;
    

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

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

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

      event.target.name]: event.target.value;

i.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:

      {
    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.

      class TestComponent extends Component {
  constructor(props) {
    super(props);
    // Declaring refs
    this.myRef = React.createRef();
  }  
  render() {
    return <element ref={this.myRef} />;
  } 
}
    

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

      this.myRef = React.createRef();
    

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

      <element ref={this.myRef} />
    

Please refer to the complete working example below.

      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;
    

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:

      ref={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.

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

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.

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

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.

Learn More

Explore these React courses from Pluralsight to continue learning: