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.
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.