Glad Chinda Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Hacking stuffs @theflutterwave.

A complete guide to React default props

6 min read 1912

React Default Props

Editor’s note: This article was last updated 6 June 2022 to address a package that is no longer actively maintained.

React is a very powerful component-based JavaScript library for building scalable applications that can run on different platforms , like the  server, web, mobile, and desktop. Thousands of applications that run on these platforms today are built on top of React.

In this article, we’ll cover setting default props for React components. The screenshots in this guide show views that are rendered with some basic Bootstrap 4 CSS styling. To get similar results, you’ll have to run the code snippets with some additional Bootstrap styles. Let’s get started!

What is a React component?

React apps are usually a composition of several independent components that make up the UI of the application. A React component is simply a JavaScript function that takes an object of arbitrary inputs known as props and returns React elements that describe what should be rendered on the UI:

// Simple React Component
function ReactHeader(props) {
  return <h1>React {props.version} Documentation</h1>
}

The example above defines a very simple ReactHeader component that renders a <h1> element containing a heading for the documentation of a specified React version. It uses the JSX syntax for creating the DOM elements hierarchy of the component in a declarative way. You can learn more about using JSX with React in the official docs.

Without JSX, the previous code snippet would be written as follows:

// Simple React Component (without JSX)
function ReactHeader(props) {
  return React.createElement('h1', null, `React ${props.version} Documentation`);
}

JSX is not required for you to use React. For example, if you intend to use React without any form of compilation, then JSX wouldn’t be the way to go. In fact, every JSX in your React component gets compiled to its createElement equivalent before the component is rendered. However, in this guide, we’ll use JSX in all components where it is possible.

From the previous code snippets, it is pretty clear that the ReactHeader component requires that a version prop is passed to it. The ReactHeader component can be rendered inside an arbitrary element on the DOM as follows:

// Render a React Component
ReactDOM.render(, document.getElementById('root'));

Notice that the ReactHeader component has been rendered with the version prop set to 16. At the moment, everything seems to be working properly in the ReactHeader component, as seen by the following screenshot:

React Header Version Prop

We made a custom demo for .
No really. Click here to check it out.

What are default props in React?

When the ReactHeader component is rendered without the version prop, the version prop is not passed:

// Render the ReactHeader Component
ReactDOM.render(, document.getElementById('root'));

Therefore, the reference to props.version in the component is undefined, as seen in the screenshot below:

React Header Version Prop Not Passed

One way you could handle this is by applying conditional rendering. Whenever a required prop is not passed, or it is invalid, you can prevent the component from rendering and render nothing instead:

// Simple React Component
function ReactHeader(props) {
  return (
    Number.isFinite(props.version)
      ? <h1>React {props.version} Documentation</h1>
      : null
  );
}

Alternately, you could set default props for the component. Default props are a way of providing default values for props that are not required by the component. For example, if you have a component that accepts a user’s name, you could use a default prop to provide a name if one is not available for that user:

const UserName = ({ name = 'User' }) => <h3 className="username">{name}</h3>

Default props can be used to define any props that you want to be set for a component, whether or not a value is actually passed in from the parent component. When using default props, you can still override the values specified in the default props object when you pass in values from the parent component.

For example, <UserName name="John Doe" /> will render John Doe, even though the default value is specified as User. The value passed from the parent component is prioritized over the default value.

According to the React documentation, defaultProps can be defined as a property on the component class itself to set the default props for the class. In our previous example, you can essentially tweak the component to use a default value for the version prop whenever it is not passed:

// With JSX
function ReactHeader(props) {
  return <h1>React {props.version || 16} Documentation</h1>
}

// OR
// Without JSX
function ReactHeader(props) {
  return React.createElement('h1', null, `React ${props.version || 16} Documentation`);
}

The logical OR operator || is used to set a fallback value for the version prop whenever it is not passed. A default value of 16 has been set for the version prop. With this change, everything now works as expected.

How to set a default prop in React

If the prop is not specified when a component is rendered, then the default prop will be used. One way to set a default prop is by destructuring the props object as follows:

const Text = (props) => {
  const {fontSize = "20px"} = props;
  return <p style={{ fontSize }}>{props.children}</p>
}

Default props are useful when you want to have a fallback prop in case the user doesn’t specify one. For example, you might want to have a default font size for a paragraph component. If the user doesn’t specify a font size, then the font size of the text will fall back to the default value.

In this guide, we’ll cover three ways of setting default props for different types of React components.

Using React.createClass() in React

In React, classes are best suited for building stateful components, in which you need to maintain state internally within the component, or in cases where you want to leverage the lifecycle methods of the component.

When React was initially released, classes had not yet become a thing in JavaScript. However, React provided the React.createClass() API for creating class-like components. Over time, this API was deprecated and finally removed from React in favor of ES6 classes.

If you’re using a React version earlier than 15.5.0, you can use the React.createClass() API to create a simple React component as follows:

import React from 'react';

/**
 * ThemedButton Component
 * Using React.createClass()
 *
 * Renders a Bootstrap themed button element.
 */

const ThemedButton = React.createClass({

  // Component display name
  displayName: 'ThemedButton',

  // render() method
  render() {
    const { theme, label, ...props } = this.props;
    return { label }
  }

});

The code snippet above creates a very simplistic ThemedButton component using the React.createClass() API. The ThemedButton component basically renders a Bootstrap-themed button based on the props passed to it.

For the ThemedButton component to properly render the button, it requires a theme prop and a label prop to be passed. Now, you can render a set of themed buttons in the React app as follows:

import React from 'react';
import ReactDOM from 'react-dom';

// [...ThemedButton component here]

function App(props) {
  return (
    <div>
      <ThemedButton theme="danger" label="Delete Item" />
      <ThemedButton theme="primary" label="Create Item" />
      <ThemedButton theme="success" label="Update Item" />
      <ThemedButton theme="warning" label="Add to Cart" />
      <ThemedButton />
    </div>
  );
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

Notice that the ThemedButton component has been rendered five times in the app. The fifth time, the ThemedButton isn’t passed any props. The app looks like the screenshot below:

Themed Button Not Passed Props

From the screenshot above, you’ll notice that the fifth button isn’t visually represented on the view since it is rendered without theme and label props. Therefore, we need to set default props for the ThemedButton component.

For components created using the React.createClass() API, you can set default props by adding a method named getDefaultProps to the object literal. The getDefaultProps() method should return an object representing the default props set for the component:

const ThemedButton = React.createClass({

  // Component display name
  displayName: 'ThemedButton',

  // render() method
  render() {
    const { theme, label, ...props } = this.props;
    return <button className={`btn btn-${theme}`} {...props}>{ label }</button>
  },

  // Set default props
  getDefaultProps() {
    return {
      theme: "secondary",
      label: "Button Text"
    };
  }

})

In the code snippet above, default props have been set for the ThemedButton component. The theme prop defaults to "secondary" if not passed, while the label prop defaults to "Button Text". With the default props set, the app should now look like the following screenshot:

Default Props Set Themed Button

Default props in React class components

In later versions of React than 15.5.0, you can create class components by leveraging the ES6 class syntax. Using the ES6 class syntax, the ThemedButton component will look like the following:

import React, { Component } from 'react';

class ThemedButton extends Component {

  // render() method
  render() {
    const { theme, label, ...props } = this.props;
    return <button className={`btn btn-${theme}`} {...props}>{ label }</button>
  }

}

For a React component created using the ES6 class syntax, you can set default props by adding a static property named defaultProps to the component class. The defaultProps static property should be set to an object representing the default props for the component. You can do so by defining defaultProps on the component class itself outside of the class body, as shown in the following code snippet:

class ThemedButton extends React.Component {
  render() {
    // ...implement render method
  }
}

// Set default props
ThemedButton.defaultProps = {
  theme: "secondary",
  label: "Button Text"
};

With the addition of static class properties and methods to the ECMAScript specification, you can alternatively specify the defaultProps, as shown in the following code:

class ThemedButton extends React.Component {
  render() {
    // ...implement render method
  }

  // Set default props
  static defaultProps = {
    theme: "secondary",
    label: "Button Text"
  }
}

Default props in React functional components

In React, the function syntax is appropriate for components that simply render elements without keeping track of their state or lifecycle. These components are usually called functional components or stateless functional components.

When re-written as a stateless functional component, the ThemedButton component will look like the following code:

import React from 'react';

function ThemedButton(props) {
  const { theme, label, ...restProps } = props;
  return <button className={`btn btn-${theme}`} {...restProps}>{ label }</button>
}

As with class components, you can set default props on a functional component by adding a static property named defaultProps to the component function itself:

function ThemedButton(props) {
  // ...render component
}

// Set default props
ThemedButton.defaultProps = {
  theme: "secondary",
  label: "Button Text"
};

Alternatively, with the ES6 object destructuring syntax, you can destructure the props of a functional component with default values. With destructured props, the ThemedButton component will look like the following code:

import React from 'react';

// METHOD 1:
// Default Props with destructuring
function ThemedButton(props) {
  const { theme = 'secondary', label = 'Button Text', ...restProps } = props;
  return <button className={`btn btn-${theme}`} {...restProps}>{ label }</button>
}

// METHOD 2:
// More compact destructured props
function ThemedButton({ theme = 'secondary', label = 'Button Text', ...restProps }) {
  return <button className={`btn btn-${theme}`} {...restProps}>{ label }</button>
}

Conclusion

Default props are a great way to make your React components reusable and easier to maintain. In this guide, we’ve covered what default props are, exploring three ways to set default props for different types of React components.

We’ve also learned how default props can be used to provide fallback values for optional props. With these tips in mind, you should be able to take full advantage of default props in your own React projects.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Glad Chinda Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Hacking stuffs @theflutterwave.

One Reply to “A complete guide to React default props”

  1. This was an absolutely MUCH easier method of explaining props, their implementations, and the multitude of ways to bring in defaults. Bookmarking this site. Thank you!

Leave a Reply