Here's an example of a React component with a "managed" input field. Whenever the value of the input field changes, an event handler is called which updates the state of the component with the new value of the input field. The call to setState
in the event handler will trigger a call to render
updating the component in the dom.
import React from 'react';
import {render} from 'react-dom';
class ManagedControlDemo extends React.Component {
constructor(props){
super(props);
this.state = {message: ""};
}
handleChange(e){
this.setState({message: e.target.value});
}
render() {
return (
<div>
<legend>Type something here</legend>
<input
onChange={this.handleChange.bind(this)}
value={this.state.message}
autoFocus />
<h1>{this.state.message}</h1>
</div>
);
}
}
render(<ManagedControlDemo/>, document.querySelector('#app'));
Its very important to note the runtime behavior. Everytime a user changes the value in the input field
handleChange
will be called and sosetState
will be called and sorender
will be calledPop quiz, after you type a character in the input field, which DOM elements change
You can experiment with this more here to find the answer