MOCKSTACKS
EN
Questions And Answers

More Tutorials









React State Events And Managed Controls


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. Every time a user changes the value in the input field

. handleChange will be called and so
.setState will be called and so
.render will be called


Pop quiz, after you type a character in the input field, which DOM elements change

1. all of these - the top level div, legend, input, h1
2. only the input and h1
3. nothing
4. whats a DOM?


Conclusion

In this page (written and validated by ) you learned about React State Events And Managed Controls . What's Next? If you are interested in completing React tutorial, your next topic will be learning about: React Default props.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.