Skip to main content

Command Palette

Search for a command to run...

Conditional wrapping in React

Updated
3 min read
Conditional wrapping in React
C

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.

This is something you do not always need, but I wrote this article for those looking for it.

Sometimes we might have a generic element, a specific component that renders inside a modal. When a specific flag is set, the component should get a parent wrapper to display it in a different variant.

We could use an if...else statement, but it looks messy.

Conditional wrapping in React

Let's say we got specific service cards to make it a bit easier to follow. In some cases, they explain a service, but in others, they need to link to a detail page.

The component might look like this.

const ServiceCard = ({ title, description, image, url }) => {
  return (
    <section>
      <h2>{title}</h2>
      <p>{description}</p>
      <img src={image} alt={title} />
    </section>
  );
};

As mentioned, what happens if we need to wrap this whole thing in a link element when the URL exists? We could use the if...else loop.

const ServiceCard = ({ title, description, image, url }) => {
  return (
    <section>
      {url ? (
        <a href={url}>
          <h2>{title}</h2>
          <p>{description}</p>
          <img src={image} alt={title} />
        </a>
      ) : (
        <>
          <h2>{title}</h2>
          <p>{description}</p>
          <img src={image} alt={title} />
        </>
      )}
    </section>
  );
};

But this shows duplicate code, so it's a bit silly. If we need to style each element, we must modify it in two places.

So how can we better wrap this conditionally?

We can create a generic component that handles this for us, the component will be named ConditionalWrapper, and it will take a condition, the wrapper, and the children it should wrap.

const ConditionalWrapper = ({ condition, wrapper, children }) =>
  condition ? wrapper(children) : children;

With that in place, we can use it on our existing component to clean it up.

const ServiceCard = ({title, description, image, url}) => {
    return (
        <section>
            <ConditionalWrapper
                condition={url}
                wrapper={children => <a href={url}>{children}</a>}
            >
                <>
                    <h2>{title}</h2>
                    <p>{description}</p>
                    <img src={image} alt={title} />
                </a>
            </ConditionalWrapper>
        </section>
    )
}

And now, if we use our component, depending on whether we pass the URL. It will render with or without the href. And the best part is that we have no duplication in our elements.

For example, the following use case:

<ServiceCard title='test' description='foo bar' img='img1.jpg' />

It would return the following HTML output:

<section>
  <h2>test</h2>
  <p>foo bar</p>
  <img src="img1.jpg" alt="test" />
</section>

We will get the following output if we put the URL in the element.

<section>
  <a href="url">
    <h2>test</h2>
    <p>foo bar</p>
    <img src="img1.jpg" alt="test" />
  </a>
</section>

Pretty cool, right?

The main magic, of course, happens in the ConditionalWrapper component and, to be precise, the wrapper argument.

Since we pass the children (which is a React default prop), we can see that the use case of our function as in wrapper={children => <a href={url}>{children}</a>} states.

  • If the condition is met
  • Wrap the children in this specific element

There will only be a handful of times when you might need this function, but it can be a huge lifesaver.

Note: big thanks to Olivier for the original idea!

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

M

Thank you so much given such a piece of valuable information. it's really helpful for me! I appreciate the author of this article sharing something special. yeah, The main magic, of course, happens in the Conditional Wrapper component and, to be precise, the wrapper argument.✔

I'm super excited to share that I have found Graphicly!

Graphicly is an all-in-one plugin for graphics management, image cropping, and image optimization. Graphicly lets you easily download and use images from the web,

whether you are on a website or on your WordPress site. With our powerful API, you can create customized libraries of images that integrate seamlessly into your theme’s header.

as a result of reading this post. I'm getting to save your profile in my favorite list. 🥰

T
Tamal Das3y ago

Loved the blog Chris !

2
C

Thanks Tamal 🙏

More from this blog

D

Daily Dev Tips

887 posts

Looking to get into development? As a full-stack developer I guide you on this journey and give you bite sized tips every single day 👊