Wednesday, 19 July, 2023 UTC


Summary

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.
The post React add wrapper component based on condition appeared first on Js Craft.