Skip to content
Related Articles

Related Articles

Improve Article

ReactJS defaultProps

  • Last Updated : 26 Mar, 2021

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.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.



Creating defaultProps in class-based 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 class-based component.

App.js




import React, { Component } from 'react';
  
class App extends Component {
  render() {
    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>
    );
  }
}
  
class Person extends Component {
  render() {
    return (
      <div>
        <p> Name: {this.props.name} </p>
        <p>EyeColor: {this.props.eyeColor}</p>
        <p>Age : {this.props.age} </p>
      </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:

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.

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :