Razvan Soare

Helper

Conditional Rendering

Have you ever wanted to render a component only if a condition is true?

Usually you would use a ternary operator, but that's not very readable. This helper is a solution to that.

JSX
...
{displayText ? <TextComponent /> : null}
...

Altho there is nothing wrong with this syntax in a big code it will make the readability of the code worse.

We can create a custom helper component like this:

JSX:TITLE=HELPERS/RENDERIF.JSX
const RenderIf = ({ isTrue = false, children }) => {
if (!isTrue) return null;
return children;
};
export default RenderIf;

Now we can use it like this:

JSX
import RenderIf from 'helpers/RenderIf'
...
<RenderIf isTrue={displayText}>
<h1>Hello There 👋</h1>
</RenderIf>

Last updated:

Jan 19, 2021