![Solving the "logical and" zero issue in JSX](/_next/image?url=%2Fimages%2Fsnippets%2Fsolving-the-logical-and-zero-issue-in-jsx%2Fcover.webp&w=3840&q=75)
Nov 07 2023
Solving the "logical and" zero issue in JSX
Issue
Logical AND of possibly zero value (renders 0)
"use client"
import { useState } from "react"
export default function ProductsInStock() {
const [productsInStock, setProductsInStock] = useState([])
return <div>{productsInStock.length && "Products in stock"}</div>
}
Fixes
Conditional (force boolean with double negation)
<div>{!!productsInStock.length && "Products in stock"}</div>
Conditional (specify length)
<div>{productsInStock.length > 0 && "Products in stock"}</div>
Ternary operator (use null)
<div>{productsInStock.length ? "Products in stock" : null}</div>