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.
- import React from 'react';
- class App extends React.Component {
- render() {
- return ( < div > < Fullname firstnameProps = "Vijai Anand"
- lastnameProps = "Ramalingam" / > < /div>);
- }
- }
- class Fullname extends React.Component {
- render() {
- return ( < div > < p > {
- this.props.lastnameProps
- }, {
- this.props.firstnameProps
- } < /p> < /div>);
- }
- }
- export default App;
-
Open main.js file and add the below code snippet.
- import React from 'react';
- import ReactDOM from 'react-dom';
- import App from './App.jsx';
- ReactDOM.render(<App />, document.getElementById('app'));
-
Open index.html file and add the below code snippet.
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <title>React App</title>
- </head>
-
- <body>
- <div id="app"></div>
- <script src="index.js"></script>
- </body>
-
- </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.