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
Oldest comments (43)
Thanks for this really good piece of code ๐
Question: When you use Conditionalwrapper inside Servicecard, is the closing
</a>
right or should it be</>
?Hi @julia
I believe that might be a typo from the author end,
</>
should be used.Ah sorry my bad, should have been the fragment closing ๐
Great idea, Chris & Olivier!
This becomes even more powerful if you make it an array of
(wrapper | false)[]
, so you can express multiple conditional wrappers in a more readable (less deep) structure:This allows you to use
P.S.: Wrote that on my cellphone, so this is untested.
Oh like that idea! ๐
I just realized this could be made even simpler using Array.prototype.reduce:
Sir you are a legend.
Was this you ? ๐
Nope, I used a normal cellphone. I don't think it would work, had I written it on that.
Great trick.
The only problem is that the
else
condition outputs invalid HTML. You shouldn't put block elements inside inline.Here is a trick how to achieve similar functionality !
codepen.io/venelinn/pen/qBKBoPo
Ah yeah didn't really pay much attention to what I wrapped for the example purpose.
Good material, Chris!
You jus't doing something unconventional method, and that metaphor really great! You're Code Freestyler!
This is the cleanest solution to conditional rendering I've seen so far!! Really clean implementation
That sounds promising! I will test this in some of my projects! Thanks!
Good thinking! Thanks for sharing
Clean code ๐คฉ
But cant we use React.CreateElement() and conditionally select element type? The last argument of the function takes children. Enlighten me if am wrong ๐ค
Not sure I follow you mean for TypeScript safety?
Could you sketch the example here?
Whole code with render. Ignore the types in the example as I have used TS. Works in JS too. Working example: stackblitz.com/edit/vitejs-vite-wb...
Ah yes would work, but less reusable I guess when needing it more than once.
Nice idea! ๐