How do you implement a controlled component in React?

In React, a controlled component is a component that has its state controlled by another component. To implement a controlled component, you will need to do the following:

  1. Initialize the state of the controlled component in the parent component and pass it as a prop to the controlled component.

  2. In the controlled component, use the value and onChange props to set the value of the input and handle changes to the input.

  3. In the onChange event handler, call a function passed down from the parent component to update the state.

Example:

class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { inputValue: '' }; } handleChange = (event) => { this.setState({ inputValue: event.target.value }); } render() { return ( <ControlledComponent value={this.state.inputValue} onChange={this.handleChange} /> ); } } class ControlledComponent extends React.Component { render() { return ( <input type="text" value={this.props.value} onChange={this.props.onChange} /> ); } }

In this example, the ParentComponent maintains the state of the input value and passes it down to the ControlledComponent as a prop. The ControlledComponent then uses the value and onChange props to set the value of the input and handle changes to the input.