How can React get the value of an input box?
To retrieve the value of an input field, you can use React’s controlled component approach. Start by defining a variable in your component’s state to store the value of the input field. For example:
constructor(props) {super(props);
this.state = {
inputValue: ''
};
}
Next, add an onChange event handler to the input box element that will update the inputValue in the state. For example:
handleChange(event) {this.setState({inputValue: event.target.value});
}
Next, bind the value of the input box to the inputValue in the state within the render method and attach the onChange event handler function to the input box. For example:
render() {return (
<input type="text"
value={this.state.inputValue}
onChange={this.handleChange.bind(this)}
/>
);}
Finally, in the event handling function, the value of the input box can be accessed by accessing inputValue in the state. For example:
handleClick() {console.log(this.state.inputValue);
}
In this way, when users enter content, the value of the input field will be stored in the state of the component and can be accessed by accessing the state to retrieve the value of the input field.