Read article Return to blog

How To Create a Custom Conditional Wrapper Component In React

Posted Oct 20, 2022

6-10 min read

For experienced React developers, conditional rendering using the ternary operator is a very powerful tool that allows your components to display two unique versions of itself based on a given condition. This comes in handy when you want to do things like display loading text/animations on the page if required data is still loading or you'd like to display a certain icon inside a component based on a local state value. Recently I found myself in a scenario where I wanted to conditionally wrap my React component inside of an element, since writing out a long ternary condition and repeat very similar code felt messy and unnecessary. In this article I'll demo how to use a much cleaner, simpler solution to conditional rendering that you might find useful in your every day React development. Let's check it out!

I'm going to use a simplified, hypothetical use-case to demonstate why a React developer might want to create conditional wrapper component in the first place. Let's say we have a component called ProductDescription that recieves a list of objects prop called items that represent bullets of text to display in an unordered list. Some of these bullets may simply be text, while others might be links that must go to an associated URL when clicked. Each item object within the items array prop is will look like the following:

item: {   text: "Example Product Description 1"urlLink: undefined };


item: {   text: "Example Product Description 2"urlLink: "" };

Our goal here is to render simple text if a given item is not a URL (urlLink is undefined), otherwise wrap the text in an anchor tag with an href set to the provided url. Here is how we could accomplish this using the usual ternary operator render methodology:

While this way of handling things works, it's definitely an eye sore and is very redundant to have to repeat the same code twice (one wrapped on an <a> element, and one without). It's lacking readability, clean formatting, and the repetition of <li> elements feels bloated. We're going to rewrite this logic with a new custom component that we'll call <ConditionalWrapper> that takes two important props:

Now let's check out this example in action!

Using our brand new <ConditionalWrapper> component we can see that the code is much more readable and there is no more repeated code in the return statement of ProductDescription. While this is a very simplified example, using the <ConditionalWrapper> in a much larger component is especially useful to mitigate repeated code and increasing readability. I hope you find this implementation technique useful and happy coding in 2023!

If you have any insights, comments, or questions about debouncing feel free to reach out to me via the contact section below. Thanks for reading!

Contact me

Tucker Massad

Boston, MA