This is the eighth part of the video series on React JS.
We continue our discussions on the basics of state in React JS. State represents the data model of a component. It’s bound to the UI. Technically, it’s just JSON data. Changing the state data using setState() method invokes the render() method. We have a button in this example, clicking which modifies the state variable, resulting in UI update
The example used in the video is given below
<html>
<head>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/jsx">
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
currentTime: new Date()
};
}
getCurrentTime() {
let currentTime = new Date();
//setState method is used to update any item in the state
this.setState({
currentTime
})
}
render() {
return (<div>
<h1>Time now: {this.state.currentTime.toString()}</h1>
<button onClick={this.getCurrentTime.bind(this)}>Get Current Time</button>
</div>);
}
}
ReactDOM.render(<Sample/>, document.getElementById("root"));
</script>
</body>
</html>
You can find the video here.
Read and watch the other parts here.