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.

    1. import React from 'react';
    2. class App extends React.Component {
    3. render() {
    4. return ( < div > < p > {
    5. this.props.lastnameProp
    6. }, {
    7. this.props.firstNameProp
    8. } < /p> < /div>);
    9. }
    10. }
    11. App.defaultProps = {
    12. firstNameProp: "Vijai Anand",
    13. lastnameProp: "Ramalingam"
    14. }
    15. 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. <head>
    4. <meta charset="UTF-8">
    5. <title>React App</title>
    6. </head>
    7. <body>
    8. <div id="app"></div>
    9. <script src="index.js"></script>
    10. </body>
    11. </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.