DEV Community

Jack Cole
Jack Cole

Posted on

Controlled Components in React

Before we even begin to look at controlled components, let's take a look at an example of an uncontrolled component.

import React from 'react';

const Form  = () => {
  <div>
    <label>
      Uncontrolled: <input type="text" />
    </label>
  </div>
}

export default Form;

This form is uncontrolled because it in no way makes an attempt to interact with the state of the component or to update the value of the input.

By having an uncontrolled form inside of our app we are allowing the opportunity for unwanted behavior in the future. We want the data that we see to exactly match the data that we have stored in our single source of truth, in this case our state and props.

So if that's the case, what is a controlled form? First let's look at another example.

import React from 'react';

class Form extends Component {
  state = {
    inputValue: ''
  }

  const handleChange = () => {}

  render() {
    return (
      <div>
        <label>
          Controlled: 
          <input type="text" value={this.state.inputValue} onChange={handleChange}/>
        </label>
      </div>
    )
  }
}

export default Form;

This one is closer, we see that we have a value in our state and that our input is displaying that value. However, this is still not controlled because we have no way to modify our state based on any change to input from our user.

import React from 'react';

class Form extends Component {
  state = {
    inputValue: ''
  }

  const handleChange = (event) => {
    this.setState({
      inputValue: event.target.value
    })
  }

  render() {
    return (
      <div>
        <label>
          Controlled: 
          <input type="text" value={this.state.inputValue} onChange= (event) => this.handleChange(event)/>
        </label>
      </div>
    )
  }
}

export default Form;

Boom. Now in addition to having our component display the current value of state we detect for any changes made to our input by calling our event handler through onChange. Whenever there is a change to that input we update our state accordingly by using the setState method. A perfect circle. Now we have total control over our data as well as maintain a single source of truth in our state.

Top comments (0)