Blog>
Snippets

Default Props for Functional Components

Showcase how to define default prop values for functional components in case no props are supplied.
// Step 1: Define a functional component with props
const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

// Step 2: Set default props for the component
Greeting.defaultProps = {
  name: 'Anonymous', // Default value for 'name' prop
};

// Step 3: Use the component
// Example usage with supplied prop:
// <Greeting name="John" />
// Output will be: Hello, John!

// Example usage without supplied prop:
// <Greeting />
// Output will be (using default prop): Hello, Anonymous!
This code defines a functional component named 'Greeting' that accepts a 'name' prop and displays a greeting message including the name. The defaultProps are set to provide a default value for the 'name' prop in case it is not passed by the parent component. The component will use 'Anonymous' as the default name. There are two example usages of the component, one with the explicit prop and one without, which will use the default prop.