Using JavaScript inline || and && logical operators together in React

Using JavaScript inline || and && logical operators together in React

In my React components I usually end up doing an inline comparison with conditional operators to determine what output to render. In these cases I can use inline if with logical && operator because React allows embedded expressions in JSX. Embedded expressions are any valid JavaScript code wrapped in curly braces and any valid piece of JavaScript that is wrapped in curly braces will execute as expected.

Here is simple example of using an inline statement in React. All this code does is render the Loading… text if the state variable isLoading is set to true.

const [isLoading, setIsLoading] = useState(true);
...
return (
    {isLoading && 
        <div>Loading...</div>
    }
)

This works because in JavaScript a true condition will always render the expression follows the conditional operator (&&). In this case isLoading returns true so anything after && is rendered. If isLoading returned false the rest of the expression would be ignored and therefore the Loading… statement is skipped.

You can also combine the && operator with || together in the same statement an AND with an OR conditional statement inline. All that’s need is to wrap the conditions in parenthesis followed by the && operator. The same logic applies here as did with the above statement. If the condition within the parenthesis is true then the following expression is rendered. If the condition is false, the following expression is then skipped.

const [isLoading, setIsLoading] = useState(true);
const [isStillLoading, setIsStillLoading] = useState(true)

useEffect(()=>{
    setIsLoading(false);
    setIsStillLoading(true);
})

return (
    {(isLoading || setIsStillLoading) && 
        <div>Loading...</div>
    }
)

This is all pretty basic after you understand how embedded expressions work in React and JavaScript. It took diving into JavaScript conditional logic to understand why the double ampersand (&&) was needed after the conditional logic. But, kind of like all language syntax, the more you try it out and learn the ideas the easier it becomes to work with.