How To Use Props In React Component

In this blog, you will see how to use props in React Component.

In this blog, you will see how to use props in React Component.

Props

Props are read-only and used for passing data from parent to child components. Please refer to Props for more details.

Prerequisites

Click here to set up development environment for React.

Steps Involved

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

    code .

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

    1. import React from 'react';  
    2. class App extends React.Component {  
    3.     render() {  
    4.         return ( < div > < Fullname firstnameProps = "Vijai Anand"  
    5.             lastnameProps = "Ramalingam" / > < /div>);  
    6.     }  
    7. }  
    8. class Fullname extends React.Component {  
    9.     render() {  
    10.         return ( < div > < p > {  
    11.             this.props.lastnameProps  
    12.         }, {  
    13.             this.props.firstnameProps  
    14.         } < /p> < /div>);  
    15.     }  
    16. }  
    17. export default App;  

     

  • Open main.js file and add the below code snippet.

    1. import React from 'react';  
    2. import ReactDOM from 'react-dom';  
    3. import App from './App.jsx';  
    4. ReactDOM.render(<App />, document.getElementById('app'));  

     

  • Open index.html file and add the below code snippet.

    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 following command to start the Server. Open the browser and type http://localhost:8080/.

npm start



Summary

In this blog, you have seen how to use props in React Component.