Solving the "logical and" zero issue in JSX

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>