How to conditionally wrap an element in React

While working on a React project, I faced a problem I didn’t encounter before: the need to have a different wrapping element based on a condition.

Olivier Steufken
Senior software engineer
React
Published
April 26, 2021

PREAMBLE

While working on a React project, I faced a problem I didn’t encounter before: the need to have a different wrapping element based on a condition.

I went through different ideas and eventually ended up creating a specific component mimicking the behaviour of a Higher Order Component.

Searching the web for improvement, I found out Kitze had shared a similar implementation a while ago.

I hope this article can help you understand how it works.

TL;DR at the end.

CASE STUDY

Here is a very simple mock-up of an online garage with cards for cars:

PROBLEM

Let’s imagine that the link prop is not mandatory and some cars don’t have it.

The way it is written right now, we would have an empty “href” attribute on our wrapping link. While it’s valid semantically, we’re adding a useless node to the DOM, which isn’t a best-practice. So let’s find a way to render it only when we actually have a link defined.

Ok we’re talking conditional rendering here and there are many ways to do that in React. For now, we’ll just use the most common technique: the ternary operator.

We check out if we have a link prop. If so, we display the card wrapped in a link, else, we wrap it in a simple div.

Done and dusted, see ya! …

… Wait a minute. There’s something really annoying here.

Duplicate code. Bummer!

I hope I don’t have to convince you how bad duplicate code is. Otherwise, just remember this quote from the ’90s:

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” (John Woods)

In order to avoid duplicate code here, we want to conditionally render the wrapping element. Let’s call that Conditional Wrapping.

SOLUTION

Let’s lay down the foundations. We have:

  • a condition (the link variable)
  • a wrapper (the link tag)
  • the children (the part of the code that will remain in both cases)

Now we’ll simply create another reusable component that will receive those 3 arguments and return a different output based on the condition. Et voilà!

Doesn’t it look nice and clean with ES6 syntax?

Small precision here is that the children prop is actually a React feature. Each component receives an implicit prop called children that contains all the elements contained between the opening tag and the closing tag where it is called. You’ll find more information here: https://reactjs.org/docs/composition-vs-inheritance.html

Let’s now implement it in our component:

Ok, this deserves a bit of explanation.

As you can see, we now wrap the content into our new ConditionalWrapper component. Thus automatically giving it the role of children.

Note that we wrapped the children in a React Fragment to avoid returning multiple elements. This could be done on the functional component itself too but I chose to kept it simple and pure. 🤷🏻‍♂️

The condition part is quite self-explanatory.

Then the tricky part is the wrapper.

It receives a function that will be called in the ConditionalWrapper component itself when the condition is true.

There it will receive the implicit children as argument. And will return what it receives wrapped in whatever we want; in this case, a link.

This small implementation is quite powerful and, though it might be a bit hard to read at first, fixes our problem of duplicate code.

TL;DR

To render a different wrapping element based on a condition, we can use this one line functional component and determine in our component when(condition) and how(wrapper) should the children be wrapped.

We’re a community-driven company that offers high-level training on the latest frameworks and technologies around JavaScript. We also love to contribute to open source and to organise free community events all around Europe!

Hackages is an educational platform with the mission of improving developers and businesses' skills and helping them acquire new ones.
Home
Tutorials
Blog
Webinars