cat ./blog/react-conditional-props-spread.mdx
React conditional props spread on a component
1 min read
I've built components where the presence of absence of a prop affects the appearance or behavior. The approach I took before I figured out the pattern I call conditional props spread used to look something like the following:
interface AcmeInterface {
title: string;
isResizable: boolean;
minWidth?: number;
maxWidth?: number;
}
export const AcmeComponent = ({ title, isResizable = false, minWidth, maxWidth }: AcmeInterface) => {
// ... do something with props
}
// Before - two instances of AcmeComponent, both with title, but only one with resizable props
export const FooComponent = () => {
const { isResizable, minWidth, maxWidth } = useResizable() ?? {};
return (
isResizable ? (
<AcmeComponent title={title} {...{ minWidth, maxWidth, isResizable }} />
) : (
<AcmeComponent title={title} isResizable />
)
)
}
// After - one component with conditional props spread pattern
export const FooComponent = () => {
const { isResizable, maxWidth, minWidth } = useResizable() ?? {};
// Less repetition - DRY and clearer intent
return (
<AcmeComponent
title="baz"
isResizable
{...(isResizable ? { minWidth, maxWidth } : {})}
/>
);
}
Why the conditional props spread pattern is better
- Legibility - it's easier to read
- Clearer intent - the logic stays with which props should be passed and which shouldn't
- DRYer than the alternative - component written out once, props specified once
cat ./comments
comments (0)
no comments yet — start the thread