Controlled Component in ReactJS

Controlled component means the value of the component is controlled by ReactJS.

It is a great way to handle forms in ReactJS. It is also recommended that you use a controlled component.

So, when you add the form elements such as <input>, <textarea> and <select>, their value is stored in state object of React component.. And when vaule of element is changed, state object of React component will also be changed only by setState() method.

Let us see how to use a controlled component.

The input tag in ReactJS

Let us try to add a textbox as a controlled component.


class App extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        name: ""
        // default value
        //name: "FirstName LastName"
      };
      this.onChangeInput = this.onChangeInput.bind(this);
    }
    onChangeInput(e){
      const { value } = e.target;
      this.setState({
        name: value
      });
    }
    render(){
        const { name } = this.state;
        return (
          <form>
            <input type="text" value={name} onChange={this.onChangeInput}/>
            <div>{name}</div>
          </form>
        );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
                    

Open above code in codepen.

You also can set the default value. Just set value of name = "FirstName LastName" in constructor() of the component.

In above code, we have added a textbox whose value is stored in state object.
We have bind onChange event to textbox. So when we make any change in textbox, it will call onChangeInput() event listener, which will change the name in state object by setState() method.

The textarea tag in ReactJS

Let us add textarea as a controlled component.


class App extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        comment: ""
        // default value
        // comment: "This is default comment"
      };
      this.onChangeTextarea = this.onChangeTextarea.bind(this);
    }
    onChangeTextarea(e){
      const { value } = e.target;
      this.setState({
        comment: value
      });
    }
    render(){
        const { comment } = this.state;
        return (
          <form>
            <textarea type="text" value={comment} onChange={this.onChangeTextarea}></textarea>
            <div>{comment}</div>
          </form>
        );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
                    

You also can set the default value. Just set value of comment = "This is default comment" in constructor() of the component.

The select tag in ReactJS

<select> creates a drop down list. If you need to select any option, you can use selected attribute in <select>. In ReactJS, you can use <select> as a controlled component as per below.


class App extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        movie: "" 
        // to set default value
        // movie : "forest_gump"
      };
      this.onChangeSelectbox = this.onChangeSelectbox.bind(this);
    }
    onChangeSelectbox(e){
      const { value } = e.target;
      this.setState({
        movie: value
      });
    }
    render(){
        const { movie } = this.state;
        return (
          <form>
            <select id="favmovie" onChange={this.onChangeSelectbox} value={movie}>
                <option value="">--Please select a movie--</option>
                <option value="forest_gump" selected>Forest Gump</option>
                <option value="shawshank_red">Shawshank Redemption</option>
                <option value="schindler_list">Schindler's List</option>
            </select>
            <div>{movie}</div>
          </form>
        );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
                    

Open above code in codepen.

You also can set the default value. Just set value of movie = "forest_gump" in constructor() of the component.

The checkbox and radio button

To use checkboxes and radio buttons as a controlled component in ReactJS, please have a look at following example.


class App extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        movie: "",
        // to set default value
        // movie : "forest_gump",
        isShowMovie: true
      };
      this.onChangeRadioButton = this.onChangeRadioButton.bind(this);
      this.onChangeCheckbox = this.onChangeCheckbox.bind(this);
    }
    onChangeRadioButton(e){
      const { value } = e.target;
      this.setState({
        movie: value
      });
    }
    onChangeCheckbox(e){
      const {checked} = e.target;
      this.setState({
        isShowMovie: checked
      })
    }
    render(){
        const { movie, isShowMovie } = this.state;
        return (
            <form>
                Select a your favorite movie:
                <div>
                    <input type="radio" id="f_g" name="movie" value={"forest_gump"} checked={movie === "forest_gump"} onChange={this.onChangeRadioButton} />
                    <label for="f_g">Forest Gump</label>
                </div>
                <div>
                    <input type="radio" name="movie" id="s_r" name="movie" value={"shawshank_red"} checked={movie === "shawshank_red"} onChange={this.onChangeRadioButton} />
                    <label for="s_r">Shawshank Redemption</label>
                </div>
                <div>
                    <input type="radio" name="movie" id="s_l" name="movie" value={"schindler_list"} checked={movie === "schindler_list"} onChange={this.onChangeRadioButton} />
                    <label for="s_l">Schindler's List</label>
                </div>
                <div>
                    <input id="isShowMovie" type="checkbox" onChange={this.onChangeCheckbox} checked={isShowMovie} />
                    <label for="isShowMovie">Show your movie to public</label>
                </div>
                { isShowMovie && 
                    <div>{movie}</div>
                }
            </form>
        );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);                      
                    

Open above code in codepen.

Conclusion

In this section, we learned about Controlled components in ReactJS.
In the next section, you will learn about Uncontrolled components in ReactJS.