šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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