Tuesday, August 7, 2018

state example in React

State in a React Component is the components data store, all data required by the component are stored in the components state. State is nothing but a JavaScript object with properties to store each state value. The initial state of the component is set on the constructor of the component. using this.state = {}. After initializing the state can be changed using setState().

In this example we will have a time property in the state which will be displayed in the component. When the component initializes the time property is set to the current date/time and the time is displayed in the component.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class HelloState extends Component {
  constructor(props) {
    super(props);
    this.state = {
time: new Date()
};
  }

  render() {
return (
  <div>
<div>
Curret Time: <b>{this.state.time.toISOString()}</b>
</div>
  </div>
);
  }
}

ReactDOM.render(<HelloState />, document.getElementById('app'));

Search Flipkart Products:
Flipkart.com

No comments: