Wrapper component for your JSX
When building any UI component, we sometimes need to wrap our entire JSX into some wrapper based on some condition. Suppose you are building a modal component and if the target prop is passed then we want to render the entire modal in a Portal else we want to render there directly.
There are multiple ways to achieve this, The Following two approaches are the ones people usually follow
Conditional Rendering of jsx

Store the entire content in a variable and do conditional rendering

What is the problem with the above two approaches?
There are two problems with the above methods
- Code readability issue
- No standard way of handling these problems
Let's talk more about these pointers below
Code Readability Issue
if we follow the first approach then we are duplicating the content. And with the second also we are dealing with the ternary approach. This will be repeated in all the components where we have this issue.
No Standard way of handling these problems
Over time when the code size grows, we repeat these sorts of patterns a lot. And at the end, the entire code will have these ternary patterns.
it is very hard also to maintain and scale these components over time.
So what is the solution to this problem?
Well to be honest we don't have any React Magic Spells here. But there is one thing we can do to avoid these patterns from impacting the entire codebase.
A cleaner solution is to use a Wrapper Component, which conditionally wraps JSX without duplicating content or using ternary operations. I encountered this problem at work when we frequently needed to wrap JSX in another element based on a prop. After comparing different approaches, I found this to be the most maintainable one.

In the above code snippet, we have three props
- shouldWrap: a boolean prop based on which we make the decision to wrap the component
- wrapperFn: a function prop that takes children as arguments and returns JSX along with wrapper
- children: children elements, in our case, it is the JSX we want to wrap
How to Use This Component
Let's take the above modal example

Conclusion
Handling conditional JSX wrapping can become messy and repetitive, especially as a codebase scales. Standard approaches like ternary operators or assigning JSX to a variable work, they can lead to readability and maintainability issues over time.
Using a Wrapper Component provides a more structured, reusable, and cleaner way to handle conditional JSX wrapping. By abstracting the wrapping logic, we avoid code duplication and improve the overall developer experience.
Next time you find yourself conditionally wrapping JSX, consider using this approach to keep your UI components more readable and maintainable
Comments ()