DEV Community

Discussion on: React Clean Code - Simple ways to write better and cleaner code

Collapse
 
pozda profile image
Ivan Pozderac • Edited

What are your thoughts about having utility component for conditional rendering like this?

<ConditionalComponent if={!!achievementsList}>
    <Achievements data={achievementsList} />
</ConditionalComponent>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thawkin3 profile image
Tyler Hawkins

Interesting! I think the only time I've used an approach like that is when using something like react-responsive and their MediaQuery component, which is basically the same idea. But for code I control, I can't say I've ever reached for this technique.

What are your thoughts? Do you like this pattern better than explicitly using ternaries or && operators?

Collapse
 
pozda profile image
Ivan Pozderac

I think it is neat way to handle conditional rendering that is OK to use for simpler cases only.

I found parts of the app that had that utility component stacked one on top of the other with various different conditions and it felt bizarre and too hacky.

I used it only recently in the code base that already had it. In all other projects I am more comfortable with using && and ternaries as I find them easier to read and understand what is going on, also feels more natural to me.

Collapse
 
adamashored profile image
adam-ashored • Edited

This is a fantastic pattern - just not for trivially simple logic.

It's a really great for passing in parameters to a component that might use some context (or other data source) whereas your parent component doesn't need to use that context. It allows all of the logic of conditional rendering to be then tucked away in one place and tested separately.

Collapse
 
pozda profile image
Ivan Pozderac

great remark, I will have to do my own research on that as your comment gave me some ideas and a different perspective on the whole thing.

Thread Thread
 
adamashored profile image
adam-ashored • Edited

By the way, this is far from a "novel" pattern, but it sounds like it might be a lightbulb moment for you in terms of separating concerns.

Take a look at some very popular conditional components that you've probably already used:

MaterialUI's Hidden component: github.com/mui-org/material-ui/blo...

It uses the theme context internally and the media-query props you provide it to determine if a child should be rendered.

React Router's Route component: github.com/ReactTraining/react-rou...

It uses the router context and the path parameter you pass in to determine if the child (or render of Component props) should be rendered.