Initialize the state of the controlled component in the parent component and pass it as a prop to the controlled component.
In the controlled component, use the
value
andonChange
props to set the value of the input and handle changes to the input.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} /> ); } }
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.
Social Plugin