- In the last post we have defined a ReactJS component in ES6 way.
- In this demo, “We will learn to define ReactJS states in ES6 flavor”.
- In ES6 flavor we have to define the initial states of a component inside the constructor function.
- In the following code we have defined a ReactJS component named MyTextComponent.It has a constructor part which takes responsibility of initialization of properties and states.It contains a state named color which is defines inside this.state object.
import React from 'react'; class MyTextComponent extends React.Component { constructor() { super(); this.state = { color: "red" }; } render() { return <h1 className={this.state.color}>Hello I am text</h1>; } } export default MyTextComponent;
- The following code shows how ReactJS component is imported in another file and rendered using ReactDOM.render() method.
import React from 'react'; import ReactDOM from 'react-dom'; import MyTextComponent from './mytext-component'; ReactDOM.render( <MyTextComponent message="Developers"/>, document.getElementById("component-container") );
- The following code contains the bundle.js file which is generated/compiled code and HTML element component-container where the MyTextComponent will be rendered.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Example3</title> <style> .red{ color:red; } </style> </head> <body> <div id="component-container"></div> <script src="bundle.js"></script> </body> </html>