DEV Community

Discussion on: 4 Ways to Render JSX Conditionally in React

Collapse
 
danwalsh profile image
Dan Walsh

One more approach you might consider adding to your list is the “guard clause”:

const MyComponent = ({name}) => { 
  if (!name) {   // 👈
    return null; // 👈 guard clause
  }              // 👈

  return <p>Hi! My name is {name}.</p>;
};

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

This conditional rendering tactic will prevent the entire component from rendering (including any unnecessary <div>s) if your conditions are not met.

Abstracting the logic from your return() statements in this way also helps by avoiding confusing nested conditionals, improving the readability of your code.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

It's not rendering <div>s it's using Fragments.

Collapse
 
danwalsh profile image
Dan Walsh • Edited

Correct—I meant that more broadly regarding returning null, not pointing to any specific examples.

Collapse
 
rasaf_ibrahim profile image
Rasaf Ibrahim

Thank you for writing about Guard Clause in details. I didn't know about this. I have modified the article and added this example under Logical Operator section as Guard Clause has ! (NOT Logical Operator).

Collapse
 
danwalsh profile image
Dan Walsh

Cheers, mate. But just to be clear, a guard clause doesn’t specifically use a NOT operator. It can be any sort of expression that, when evaluated to be false (or falsy, depending on your logic), returns the function early.

Thread Thread
 
rasaf_ibrahim profile image
Rasaf Ibrahim

Very useful information, thank you. 😃

Collapse
 
k1dv5 profile image
Kidus Adugna

Why not just return instead of return null?

Collapse
 
danwalsh profile image
Dan Walsh

If I remember correctly, return on its own infers a return type of void, whereas return null is an acceptable React.ReactNode return type, as far as TypeScript is concerned.

Thread Thread
 
fjones profile image
FJones

And void in turn results in undefined on the caller, which React now supports, but I would still discourage. The reason support for it was added was, in part, inconsistency between nested and root-level conditional rendering.

Collapse
 
rasaf_ibrahim profile image
Rasaf Ibrahim

Yes, you can definitely do that as we know whenever JavaScript sees the return keyword, it immediately exits the function.