Author -  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;

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY