Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 11

Setting Default Props with JavaScript Parameters

Recommended resources

Hello! Let's continue our journey into building robust React components.

Introduction

In our previous lesson, we learned the crucial skill of passing data down from parent to child components using props and how to define their "shape" with TypeScript interfaces for type safety. We established that interface is the preferred method for component props due to its performance and clarity.

But what happens when a prop is optional? If a parent component doesn't provide a value for an optional prop, it will be undefined inside the child component. This can lead to unexpected behavior, visual bugs, or even runtime errors.

Today's lesson directly addresses this by focusing on the learning outcome: Define default props for a component using JavaScript default parameter syntax. We'll explore the modern, clean, and recommended way to ensure your components have sensible fallback values, making them more resilient and predictable.


The Problem: Optional Props and undefined

Let's revisit the UserProfileCard component from our last lesson's exercise. Suppose we want to add an optional status prop that can be 'online', 'offline', or 'away'.

First, we update our props interface to include this optional property:

export interface UserProfileCardProps {
  name: string;
  age: number;
  isVerified: boolean;
  status?: 'online' | 'offline' | 'away'; // This prop is optional
}

Now, let's try to use this status prop to display an indicator:

const UserProfileCard = ({ name, age, isVerified, status }: UserProfileCardProps) => {
  // A helper function to get the color based on status
  const getStatusColor = (s: 'online' | 'offline' | 'away' | undefined) => {
    if (s === 'online') return 'green';
    if (s === 'away') return 'orange';
    return 'grey'; // Default for 'offline' or undefined
  };

  return (
    <div style={{ border: '1px solid #ccc', padding: '16px', borderRadius: '8px' }}>
      <h3>
        {name} 
        <span style={{ 
          display: 'inline-block', 
          width: '10px', 
          height: '10px', 
          borderRadius: '50%', 
          backgroundColor: getStatusColor(status), 
          marginLeft: '8px' 
        }}></span>
      </h3>
      <p>Age: {age}</p>
      {isVerified && <span style={{ color: 'green' }}>✓ Verified</span>}
    </div>
  );
};

If a parent component renders <UserProfileCard ... /> without the status prop, status inside the component will be undefined. Our getStatusColor function handles this case, but the logic is now inside the component's render body. A cleaner approach would be to ensure status always has a valid value.


The Modern Solution: Default Parameter Syntax

Since you're fluent in modern JavaScript, you'll already be familiar with ES6 default parameters for functions. React functional components are just functions, so we can leverage this feature directly.

We can assign a default value right where we destructure the props:

const UserProfileCard = ({ 
  name, 
  age, 
  isVerified, 
  status = 'offline' // Default value assigned here
}: UserProfileCardProps) => {
  // ... the rest of the component
};

With this single change, if the status prop is not provided, it will automatically be set to 'offline'. This simplifies the component's internal logic and makes its behavior more robust.

The official React documentation provides a clear and concise explanation of this technique.

Passing Props to a Component

Let's look at the official React documentation for a definitive guide on this pattern. It's the standard and recommended way to handle default values.

Please read the section titled 'Specifying a default value for a prop'. Crucially, take note of the distinction it makes: the default value is only used if the prop is missing or passed as undefined. It is not used if you explicitly pass null or 0.

This distinction is key. For example:

  • <MyComponent /> or <MyComponent value={undefined} /> → value uses the default.
  • <MyComponent value={null} /> → value is null.
  • <MyComponent value={0} /> → value is 0.

This behavior is a feature of JavaScript itself and is exactly what you typically want when working with React props.


Combining Optional Props and Default Values in TypeScript

Let's look at a practical example that neatly ties together TypeScript's optional properties and JavaScript's default parameters.

React with TypeScript: Best Practices

This article on SitePoint provides a great, self-contained example of a Button component that demonstrates how to define an optional prop in TypeScript and then provide a default for it in the component implementation.

Find the 'Props' section and focus on the final code block that defines the Button component. Pay attention to how the color prop is defined as optional with a ? in the type definition, and then assigned a default value (color = 'tomato') during destructuring.

As shown in the article, the pattern is straightforward:

  1. In the interface or type: Mark the prop as optional with ?.
    interface ButtonProps {
      color?: string; // Optional
      // ... other props
    }
    
  2. In the component signature: Provide a default value using =.
    const Button = ({ color = 'tomato', ... }: ButtonProps) => {
      // ... component logic
    }
    

This combination gives you the best of both worlds: TypeScript enforces type safety, while JavaScript provides a clean, declarative way to handle missing values.

Test your understanding!

You are building a ProgressBar component. It should accept two props:

  1. progress: A number from 0 to 100 representing the percentage complete.
  2. color: An optional string for the bar's color.

Requirements:

  1. Define a ProgressBarProps interface.
  2. The color prop should be optional.
  3. If color is not provided, it should default to '#007bff' (a standard blue).
  4. The component should render a div that visually represents the progress bar.

Write the ProgressBar component and its props interface.

Show answer

Here is a correct implementation:

import React from 'react';

// 1. Define the props interface with an optional 'color'
export interface ProgressBarProps {
  progress: number;
  color?: string;
}

// 2. Assign a default value to 'color' in the function signature
const ProgressBar = ({ progress, color = '#007bff' }: ProgressBarProps) => {
  // Ensure progress is within the 0-100 range
  const clampedProgress = Math.min(Math.max(progress, 0), 100);

  const containerStyles: React.CSSProperties = {
    height: '20px',
    width: '100%',
    backgroundColor: '#e9ecef',
    borderRadius: '4px',
  };

  const fillerStyles: React.CSSProperties = {
    height: '100%',
    width: `${clampedProgress}%`,
    backgroundColor: color, // Use the color prop (which has a default)
    borderRadius: 'inherit',
    textAlign: 'right',
    transition: 'width 0.6s ease-in-out',
  };

  return (
    <div style={containerStyles}>
      <div style={fillerStyles}></div>
    </div>
  );
};

// Example usage:
const App = () => (
  <div>
    <h4>Default Color:</h4>
    <ProgressBar progress={60} />
    
    <h4>Custom Color:</h4>
    <ProgressBar progress={80} color="green" />
  </div>
);

export default ProgressBar;

Historical Context: Older Methods

For a comprehensive understanding, it's useful to know about older patterns for setting default props, as you may encounter them in legacy codebases or older tutorials. The default parameter syntax is relatively new (in the grand scheme of JavaScript), and other methods were used before it became standard.

This image provides an excellent visual contrast between the modern approach and the older defaultProps static property.

Comparing Default Props Definition Methods in React
A comparison of the modern ES6 default parameter syntax (top) versus the older `defaultProps` static property (bottom) for defining default prop values in a React component.

The defaultProps property was the standard way to define defaults for a long time, especially with class components. While it still works on functional components, it's less direct and has been largely superseded by default parameters.

Another common pattern is using the logical OR (||) operator inside the component body:
const finalColor = color || 'tomato';
This works, but it has a known pitfall: it treats any "falsy" value (like 0, an empty string '', or false) as a reason to use the fallback. Default parameters only trigger for undefined, which is usually the desired behavior.

The following video walks through all three methods. While we've already mastered the best one, seeing the others in action will solidify your understanding.

A complete guide to default props in React

This video guide demonstrates three different ways to set default props. We have focused on the best and most modern method, but it's valuable to recognize the alternatives.

You can quickly review the different approaches discussed in the video: defaultProps static property (Legacy): Watch from 01:44 to 03:33. Logical OR (||) operator: Watch from 03:33 to 04:28. Default Parameters (Modern & Recommended): Watch from 04:28 to 05:22 to see a recap of what we've learned.


Conclusion

You've now learned how to make your components more robust and self-contained by providing default values for optional props. This simple technique cleans up your component logic and prevents a common class of bugs.

Key Takeaways:

  • Optional props are undefined inside a component if not provided by the parent.
  • The modern and recommended way to provide fallbacks is using JavaScript's default parameter syntax directly in the component's destructuring signature (e.g., ({ prop = 'defaultValue' })).
  • This pattern works seamlessly with TypeScript's optional properties (prop?: type).
  • The default value is applied only for undefined or missing props, not for null or other falsy values.
  • Older patterns like the defaultProps static property and the logical OR (||) operator exist but are generally not preferred for new functional components.

Next Steps

So far, we've passed data to components as named attributes in JSX, like <User name="Satoshi" />. But what if we want to pass a chunk of JSX into another component, like we do with standard HTML tags (<div><p>Hello</p></div>)? In our next lesson, we will explore the special children prop, which allows us to create flexible and powerful wrapper components.