Sitemap
Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Member-only story

Stop Using “&&” for Conditional Rendering in React Without Thinking

4 min readOct 7, 2022

--

Photo by Joshua Hoehne on Unsplash

If you’ve seen any React application, you know how to conditionally render parts of a component depending on props and state. Although there are multiple ways of conditional rendering, this article focuses on the JavaScript && operator. The main reason for this emphasis is that the&& operator often leads to UI bugs, which can be easily avoided and it’s often not mentioned.

Content

· How “&&” Works
· Why Not To Use “&&”
· What To Use Instead Of “&&”
· Best React Books and Courses in 2023

How “&&” Works

A classic example of its use in React would be:

function MyComponent({ condition }) {
return (
<div>
<h1>Title</h1>
{condition && <ConditionalComponent />}
</div>
);
}

Briefly summarized:

  • if condition is a truthy value, <ConditionalComponent /> is rendered
  • if condition is a falsy value, <ConditionalComponent /> is not rendered

--

--

Jakub Kozak
Jakub Kozak

Written by Jakub Kozak

👨‍💻 Senior Frontend Engineer 🟢 Support me by becoming a Medium member: https://bit.ly/3VPCuqA ☕ Or let's grab a coffee: https://ko-fi.com/jakubkozak