Reputation: 1342
What is the best approach for adding optional components inside a component?
I have one like this:
type Props = {
children: React.Node,
title?: string,
/**May add any component next to the header. Should be inside a fragment. */
headerComponents?: React.Node,
className?: string,
}
export const Content = ({ children, className, title, headerComponents }: Props) => (
<div className={`page-content ${className}`}>
<div className='page-content-header'>
{
title && (
<h2 className='content-title'>{title}</h2>
)
}
{
headerComponents && (
<div className='page-header-right'> {headerComponents} </div>
)
}
</div>
{children}
</div>
);
The headerComponent
acts as a prop that can receive another component, like this:
<Page.Content
headerComponents={
<>
<Button>First</Button>
<Button>Second</Button>
</>
}
title='Example title'
>
<div>Example text</div>
</Page.Content>
And it works. But I'm wondering if there's a better approach.
Upvotes: 0
Views: 288
Reputation: 42516
This approach looks fine to me. It is readable and intuitive to pass props to the component, followed by conditionally rendering the optional components based on the values of the props.
Upvotes: 3