How to set default props in React
Setting default props is essential for creating robust React components that handle missing or undefined prop values gracefully while providing sensible fallbacks. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented default props in thousands of React components to ensure reliable behavior, backward compatibility, and excellent developer experience in enterprise component libraries. From my expertise, the most modern approach is to use ES6 default parameters in function components. This method provides clear, readable code with TypeScript support while eliminating the need for runtime checks and additional component properties.
Use ES6 default parameters in function components for clean and TypeScript-friendly default props.
// Modern approach with ES6 default parameters
function Button({
children = 'Click me',
variant = 'primary',
size = 'medium',
disabled = false,
onClick = () => {},
type = 'button'
}) {
const buttonClass = `btn btn-${variant} btn-${size}`
return (
<button
className={buttonClass}
disabled={disabled}
onClick={onClick}
type={type}
>
{children}
</button>
)
}
// TypeScript version with interface
interface ButtonProps {
children?: React.ReactNode
variant?: 'primary' | 'secondary' | 'danger'
size?: 'small' | 'medium' | 'large'
disabled?: boolean
onClick?: () => void
type?: 'button' | 'submit' | 'reset'
}
function TypedButton({
children = 'Click me',
variant = 'primary',
size = 'medium',
disabled = false,
onClick = () => {},
type = 'button'
}: ButtonProps) {
return (
<button
className={`btn btn-${variant} btn-${size}`}
disabled={disabled}
onClick={onClick}
type={type}
>
{children}
</button>
)
}
// Usage - all props are optional due to defaults
// <Button />
// <Button variant="danger" size="large">Delete</Button>
ES6 default parameters provide the cleanest syntax for default props in modern React. Destructure props in the function parameter list and assign default values directly. This approach works seamlessly with TypeScript by marking props as optional in the interface. Default parameters are applied when props are undefined
, providing predictable behavior. This eliminates the need for the legacy defaultProps
static property while providing better performance and clearer code intent.
Best Practice Note:
This is the same approach we use in CoreUI React components for clean, type-safe default prop handling. Use object destructuring with defaults for better readability, make props optional in TypeScript interfaces when they have defaults, and consider using union types for constrained prop values like button variants or sizes.