Inline conditional rendering in React.js

Srishty M
2 min readNov 26, 2023

--

conditional rendering example

Recently, the new documentation of React has been released, which you can find on React.dev site.

That’s what made me write about this short post. If you’ve just started learning React, you must have come across a syntax, which looks something like this:

return (<>
{(unreadMsgs.length > 0) &&
<h2>You have {unreadMsgs.length} unread messages.</h2>
}
</>);

That’s basically used as short-hand for the following code:

if(unreadMsgs.length > 0){
return(
<h2>You have {unreadMsgs.length} unread messages.</h2> );
}

You must be wondering how does that work! And why do we use the && operator here?

So let’s look for what’s the logic behind using && operator. The reason is that in JavaScript,

true && 'something'

is ‘something’.

And to understand this, you should have paid attention in the basic electronics class, where they taught ‘boolean algebra’.

W.K.T. ,

considering for example ‘a’ as a variable representing varying values , can be anything either true or false,

false AND a

is always false. And,

true AND a 

is equal to a. i.e., the result is dependent on ‘a’.

And that’s how this can be explained. I hope the logic behind inline conditionals is understood.

Apart from that, we can also use ternary operator for our components, for example:

return (
<>
{ isLoggedIn ? <DashBoard/> : <SignIn/> }
</>
);

is equivalent to:

if (isLoggedIn) {
return <DashBoard/>;
}
return <SignIn/>;
}

Happy learning!

--

--

Srishty M
Srishty M

Written by Srishty M

Just a normal human with great ambitions and can't help overthinking :) https://srishty-portfolio.netlify.app/

No responses yet