DEV Community

Cover image for Conditional rendering in React
Tomek Poniatowicz for GraphQL Editor

Posted on • Updated on

Conditional rendering in React

I recently saw some posts and comments about conditional rendering in React and to my surprise some of them stated && was outdated and should be dropped in favor of using if/else, : ? and || conditions. It struck me as odd as from what (admittedly little) I have learned so far AND is fine and in some cases simply more straightforward. Especially when compared with sticking nulls everywhere just to avoid using it. Far be it from me to criticize anyone but I decided this would be a good idea to elaborate more on conditional rendering in React.

if/else and ternary operator :?

This is most likely the first type of conditional you’ve learned, honestly I didn't even know it was called a ternary operator until writing this as I’ve heard our devs simply call it an ‘if’ or ‘conditional’. Both are very straightforward and work pretty much the same although with a slightly different syntax:

PowerLevel  > 9000 
? console.log(Its over 9000!!!) 
: console.log(PowerLevel)
Enter fullscreen mode Exit fullscreen mode

or

if (PowerLevel > 9000)
{console.log(Its over 9000!!!)}
else
{console.log(PowerLevel)}
Enter fullscreen mode Exit fullscreen mode

Both of these will do exactly the same thing but the syntax is slightly different. For a simple thing like this the ternary operator is just more succinct and makes more sense to use. It's obviously down to personal preference but from what I’ve heard from devs the rule of thumb is:

  • use :? for smaller things that can fit in one line or two (eg. for registered users show a button with “Log in” and for unregistered show it with “Register”)
  • use if/else statements for executing bigger segments of code (like say a different navbar for desktop and mobile versions of a website)

Just to give you a real example this is a simple code snippet from our language switcher:

push(pathname.replace('[locale]', newLang === 'en' ? '' : newLang));
Enter fullscreen mode Exit fullscreen mode

It's pretty simple - when the user selects a language from the dropdown it pushes the user to the selected language version of the page adding the locale tag to the url address, but omitting it if it's the default language ie. English. (sidenote here: this is actually very important for SEO as I’ve had multiple issues with language selectors adding a default locale tag to the url which caused example.com and example.com/en to be flagged as duplicate pages)

While using ternary and if/else is the go-to it can be overused because of that, as sometimes other conditionals make more sense. Take this simple snippet for a metaDescription meta tag in my custom helmet - it uses the provided metaDescription if there is one and a fallback value if it is not provided:

<meta
  name="description"
  content={metaDescription ? metaDescription : defaultDescription}
/>
Enter fullscreen mode Exit fullscreen mode

OR (||) condition

While that works fine I’ve actually started using OR conditions for cases like this since they are simpler and quicker to write. From my experience this is used way too little since you get tons of situations like this (especially when dealing with websites) where you just need one value and a default fallback just in case. Following the above metaDescription example we can just use this to get the exact same result:

<meta name="description" 
content={metaDescription || defaultDescription} />
Enter fullscreen mode Exit fullscreen mode

It will simply always use a metaDescription if one is provided, and fallback to the default one if it is not, which is perfect for use cases like this. Yes you can use multiple || and it will simply always render the first one that is true, but I think that’s overusing it since you can't specify different conditions for each one anyway and at that point using a ternary condition or if/else makes more sense anyway. You can also use || with a null for an element you only want to render under certain conditions, but for that case && actually makes more sense in my opinion.

AND (&&) condition

Like I said before I have seen some claims && is outdated, which surprised me since I consider it by far the cleanest to use when I want to render an element only under certain conditions. It works the simplest of all of the ones I mentioned here as it just does nothing if the condition is not fulfilled. Yeah you can do that with the others - just use a null and you’ll likely get the same result - though writing nulls everywhere just for the sake of avoiding && seems pointless.

Sure you can get a displayed 0 error like the one on the screen below:

a big oopsie

Obviously if you’re afraid you might get one for something like products.length on your ecommerce store it's also pointless to force yourself to use && just for the sake of it - it's way better to go with what you feel more comfortable with. That said, this particular error was solved by simply using !! to force a boolean representation and the && was left untouched - which goes to show once again that all this comes down to what you're most comfortable using.

For me I can say that on the SEO side I’ve fixed enough bugs and issues where someone forgot to add a null and I had off-screen or hidden elements picked up by crawlers. If you like the seo guys in your workplace you can be nice and save them an hour or so which they might otherwise spend looking for a mobile langSwitcher with a 404 link which was hidden somewhere on the desktop version of the page. So for a simple component that you want rendered only if a certain condition is fulfilled && is still perfectly fine in my opinion. Here's an example case of where I use it in my custom helmet element:

{
  LocalizedPage && (
    <>
      {hrefLangs.map((lang) => (
        <link
          key={lang}
          rel="alternate"
          hrefLang={lang}
          href={`https://example.com/${lang}${location}`}
        />
      ))}
      <link
        rel="alternate"
        hrefLang={defaultLang}
        href={`https://example.com${location}`}
      />
      <link
        rel="alternate"
        hrefLang="x-default"
        href={`https://example.com${location}`}
      />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

As you can see that is even simpler than the others - only render this code if the page is localized. I don't have to specify the outcome for false or a fallback null value - I just say this is solely for that condition and that's it. This is a simple way of ensuring I have alternate links included in the head for pages which are translated into other languages, while making sure they won't appear in the dom for those which aren't translated (like say blogposts) which would be flagged as a SEO error. I think it's also a good approach to keep things as simple as possible when it comes to seo so if I go into someone’s frontend code to add this little element they figure out exactly what this is intended for at a glance.

Obviously if you’re comfortable with using if/else everywhere and that works for you there's no reason to force yourself to use something else, even if it can make more sense in certain situations. But as you can see in using OR or AND can be handier so it's perfectly fine to use those as well, they are in no means outdated or wrong if used correctly.

Top comments (0)