In this blog, you will see how to set default props on React Component.
Props
Props are read-only and used for passing data from parent to child components. Please refer 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 > < p > {
- this.props.lastnameProp
- }, {
- this.props.firstNameProp
- } < /p> < /div>);
- }
- }
- App.defaultProps = {
- firstNameProp: "Vijai Anand",
- lastnameProp: "Ramalingam"
- }
- 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 set default props on React Component.