Creating defaultProps in Functional Component
Now write down the following code in the App.js file. Here, App is our default component where we have written our code using a functional component.
Example: This example creates defaultProps in Functional Components
App.js
import React from 'react' ; function App(props) { return ( <div > <Person name= "kapil" eyeColor= "blue" age= "23" ></Person> <Person name= "Sachin" eyeColor= "blue" ></Person> <Person name= "Nikhil" age= "23" ></Person> <Person eyeColor= "green" age= "23" ></Person> </div> ); } function Person(props) { return ( <div> <p> Name: {props.name} </p> <p>EyeColor: {props.eyeColor}</p> <p>Age : {props.age} </p> <hr></hr> </div> ) } Person.defaultProps = { name: "Rahul" , eyeColor: "deepblue" , age: "45" } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
ReactJS defaultProps
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.