React Controlled Component Example


A Controlled component is a component in which the value of the input field is controlled by React state. The component itself manages the state of the input and updates the state when the user interacts with the input field. Controlled components use the value attribute of the input element to receive the value from the state and use the onChange

Controlled components are useful when you need to perform validation on the input before submission or when you need to manipulate the input value

Here’s an example of a Controlled Component in React:

import React, { Component } from 'react';

class ControlledComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  handleInputChange = (event) => {
    this.setState({ inputValue: event.target.value });
  }

  handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value: ', this.state.inputValue);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Enter a value:
          <input
            type="text"
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />
        </label>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

export default ControlledComponent;

In this example, we have a ControlledComponent that manages the state of an input field. The ControlledComponent has a state that consists of an inputValue variable, and two methods to handle changes to the input value and the submission of the form.

The ControlledComponent renders a form with an input field and a submit button. The input field is a controlled component because it receives its value from the state of the ControlledComponent and updates the state when the user types in it.

The handleInputChange method is called when the user types in the input field. It updates the state of the ControlledComponent with the new value of the input field.

The handleSubmit method is called when the user submits the form. It logs the value of the input field to the console.

Overall, the ControlledComponent manages the state of the input field and handles the submission of the form. This makes it easier to manage the form data and perform validation on the input before submission.