DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Creating a Controlled Input

  • Our application may have more complex intteractions between state and the rendered UI. Ex, form control elements for text input such as input and textarea, maintain their own state in the DOM as the user types. With React, we can move this mutable state into React Component's state. The user's input becomes part of the application state, so React controls the value of that input field. Usually will be a controlled input form.
  • FreeCodeCamp provided us with the code Editor which looks like this right now.
class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    // Change code below this line

    // Change code above this line
  }
  // Change code below this line

  // Change code above this line
  render() {
    return (
      <div>
        { /* Change code below this line */}

        { /* Change code above this line */}
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode
  • There's a skeleton of a component called ControlledInput to create a controlled input element. Component's state as a input property with a empty string. That value represents the text a user types into the input field.
  • First they want us to create a method called handleChange() that has a parameter called event. When it's called it receives an event object that contains a string of text from input element. We can access this sting with event.target.value inside the method.
  • Second in the render method, let's create the input element added a value attribute which is equal to the input property of the component's state. Then add an onChange() event handler set to the handleChange() method.
  • Answer:
class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      input: event.target.value
    })

  }

  render() {
    return (
      <div>
        <input value = {this.state.input} onChange = {this.handleChange}></input>
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode
  • What will happen is when you type in the input box, that text is processed by the handleChange() method, set as the input property in the local state. and rendered as the value in the input box on the page.

Top comments (0)