Subscribe

Conditional wrapping in React

✍️

Learning how to conditionally wrap a React element

11 Dec, 2022 · 4 min read

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} />
        </>
      </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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Have you tried React classnames?

26 Oct, 2022 · 2 min read

Have you tried React classnames?

Passing className to components in React

25 Oct, 2022 · 2 min read

Passing className to components in React

Join 2099 devs and subscribe to my newsletter