- We can create ReactJS component using ES6 class concept.
- In this demo, “We will learn to create ReactJS component in ES6”.
- In ES6 a class can be defined using class keyword and can inherit another class using extend keyword.
- To define a ReactJS component in ES6 the component must be defined as a class and must extend React.component class.
- The following code(welcome-component.js) defines a ReactJS component named WelcomeComponent which extends the React.component.The WelcomeComponent has a property named message.
import React from 'react'; class WelcomeComponent extends React.Component { render() { return <h1>Welcome {this.props.message}!</h1>; } } export default WelcomeComponent;
- 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 WelcomeComponent from './welcome-component'; ReactDOM.render( <WelcomeComponent 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 WelcomeComponent will be rendered.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Example1</title> </head> <body> <div id="component-container"></div> <script src="bundle.js"></script> </body> </html>