by Sai gowtham

Setting a Default Value to the props in React

In this tutorial, we are going to learn about how to set a default value to the props in React using defaultProps object.

Props

In react, props help us to pass the data from a parent component to the child component, but if we forgot to pass a prop value to child component react doesn’t render anything into the dom.

To solve this problem, we can set a default value to the prop using defaultProps, so that react renders it whenever we don’t pass a prop value from the parent component.

Setting a Default value using defaultProps

To set a default value to the prop, we need to add properties to the defaultProps object.

Welcome.js
import React from "react";

export default function Welcome(props){
    return <h1>Welcome {props.name}</h1>
}

// setting default value to name prop
Welcome.defaultProps = {
    name: "Boss"}
App.js
import React from "React";
import Welcome from "./Welcome";
export default function App() {
  return (
    <div>
      <Welcome />      <p>My first react app</p>
    </div>
  );
}

In the above code, we are not passing a name prop to the Welcome component, so that react uses the default prop value we defined inside the Welcome component.

default props in react

In class-based components, we can use the defaultProps as a static property to set the default values.

Welcome.js
import React, {Component} from "react";

class Welcome extends Component {
  static defaultProps = {
    name: "king",  };

  render() {
    return <h1>Welcome {this.props.name}</h1>;
  }
}

export default Welcome;

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course