Conditional wrapping in React

Read Time:2 Minute, 19 Second

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.

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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:

Enter fullscreen mode Exit fullscreen mode

It would return the following HTML output:

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Source: https://dev.to/dailydevtips1/conditional-wrapping-in-react-46o5