šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React add wrapper component based on condition

In order to have a given React component wrapped another component based on some condition we can use a pattern like the one below:

const WrapperConditional = ({ condition, wrapper, children }) =>
    return condition ? wrapper(children) : children;
}
const App = () => {
    return (
      <WrapperConditional
              condition={true}
              wrapper={children => <a href="#">{children}</a>}
       >
        <p>šŸ“¦ Main component here</p>
      </WrapperConditional>
    )
}                 

The WrapperConditional is a higher-order component. It takes a component and returns a new component while reusing some logic.
React add wrapper component based on condition

In this case, the <p>šŸ“¦ Main component here</p> will be wrapped by a <a href="#"></a> if the condition property is set to true.

Using the wrapper property we can customize the wrapping component. For example:

wrapper={children => (<div style={{ background: 'green' }}>{children}</div>)}

As usual, you can see the full example running on GitHub Pages and the code is on my GitHub.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *