0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.