Logical operators in React are used to combine or modify boolean values or expressions. They are often used in conditional rendering, where we want to show or hide certain parts of a component based on a condition. While they do have their drawbacks, if you think through your code and the requirements at hand, they are a great way to clean up your code
Logical AND &&
Let’s say you need to make a component where a title and text are rendered. The text only renders if the text
prop is truthy. You would probably write something like this
import React from 'react'; const TitleWithText = ({title, text}) => { ( <div> <h1>{title}</h1> {text ? <p>{text}</p> : null} </div> );
Using the logical AND this code can be re-written like
import React from 'react'; const TitleWithText = ({title, text}) => ( <div> <h1>{title}</h1> {text && <p>{text}</p>} </div> );
Logical OR ||
Let’s say you need to make a component where a text is rendered, but if no text is found, you want to default to some string. You would probably write something like this
const MyComponent = ({text}) => ( <div> <p>{text ? text : "Default text"}</p> </div> );
Using the logical OR this code can be re-written like
const MyComponent = ({text}) => ( <div> <p>{text || 'Default text'}</p> </div> );