Define defaultProps near your props in JS
Let’s look at how to define your React JavaScript default prop values at the top of your file and why that makes them a little easier to use.
The common approach
When defining default values for your props in React, the common approach demonstrated online is to define your defaults at the bottom of your component.
export function ConfirmationModal(props) {
const {
title,
description,
} = props;
/* Other stuff */
return (
<div>
<h2>{title}</h2>
<p>{title}</p>
</div>
);
}
ConfirmationModal.defaultProps = {
title: 'Delete file',
description: 'Are you sure?',
};
I’ve never liked that approach because it can often place your defaults far down the file and far away from where you usually destructure and accept the props themselves.
My recommendation
Instead of way down the bottom, I opt for defining my defaultProps just above the function where it’s right where I’ll be when I want to check them. This means you have to define them in a variable that you then assign to the components defaultProps at the bottom.
Notice how this keeps your defaults right near the destructuring of the props as well, so all the related elements are close together.
const defaultProps = {
title: 'Delete file',
description: 'Are you sure?',
}
export function ConfirmationModal(props) {
// destructuring
const {
title,
description,
} = props;
/* Other stuff */
return (
<div>
<h2>{title}</h2>
<p>{description}</p>
</div>
);
}
ConfirmationModal.defaultProps = defaultProps;
Even if you don’t destructure your props and instead use them directly from the props parameter, I’ve found that destructuring anyway, but commenting it out, allows for greater visibility of the intended props — Which helps prevent errors.
It’s a nice little helper that makes it easier to understand your files at a glance even if you’re not using TypeScript yet.
const defaultProps = {
title: 'Delete file',
description: 'Are you sure?',
}
export function ConfirmationModal(props) {
// const {
// title,
// description,
//} = props;
/* Other stuff */
return (
<div>
<h2>{props.title}</h2>
<p>{props.description}</p>
</div>
);
}
ConfirmationModal.defaultProps = defaultProps;
That’s it!
You can probably guess that I’ve moved on to favouring TypeScript over JavaScript, but hopefully this helps those of you starting out or still using JavaScript.
Thanks…
I also dissect and speculate on design and development.
Digging into subtle details and implications, and exploring broad perspectives and potential paradigm shifts.
Check out my conceptual articles on Substack or find my latest below.
You can also find me on Threads, Bluesky, Mastodon, or X for more diverse posts about ongoing projects.