How To Create A Component In React Using Es6

Components

Components are conceptually similar to JavaScript functions, which are used to split UI into independent, reusable pieces and think about each piece in an isolation. It is easy to maintain and you can update the specific component without affecting the rest of the page. Please refer Components for more details.

Prerequisites

Click here to set up the development environment for React.

Steps involved are given below.

  • Open the root folder in Visual Studio Code by running the command given below.

  • Open App.jsx file and add the code snippet given below.

  1. import React from 'react';  
  2.   
  3. class App extends React.Component {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.                <FirstName/>  
  8.                <LastName/>  
  9.             </div>  
  10.         );  
  11.     }  
  12. }  
  13.   
  14. class FirstName extends React.Component {  
  15.     render() {  
  16.         return (  
  17.             <div>  
  18.                 <p>First Name: Vijai Anand</p>  
  19.             </div>  
  20.         );  
  21.     }  
  22. }  
  23.   
  24. class LastName extends React.Component {  
  25.     render() {  
  26.         return (  
  27.             <div>  
  28.                 <p>Last Name: Ramalingam</p>  
  29.             </div>  
  30.         );  
  31.     }  
  32. }  
  33.   
  34. export default App;   
  • Open main.js file and add the code snippet given below.

  1. import React from 'react';  
  2. import ReactDOM from 'react-dom';  
  3. import App from './App.jsx';  
  4.   
  5. ReactDOM.render(<App />, document.getElementById('app'));   
  • Open index.html file and add the code snippet given below.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.   
  4. <head>  
  5.     <meta charset="UTF-8">  
  6.     <title>React App</title>  
  7. </head>  
  8.   
  9. <body>  
  10.     <div id="app"></div>  
  11.     <script src="index.js"></script>  
  12. </body>  
  13.   
  14. </html>   

Testing

Run the command given below to start the Server. Open the Browser and type http://localhost:8080/

npm start


Summary

In this blog, you had seen how to create a simple component in React, using ES6.
Ebook Download
View all
Learn
View all