Conditional rendering

Show or hide things with && and ? :

Key points

  • You can't write if inside { } in JSX. Use && or ? : instead
  • To show or hide something, use &&: {isOpen && <p>Content</p>}
  • To show either A or B, use ? :: {isLoggedIn ? <p>Welcome</p> : <p>Please log in</p>}

Try it

import { useState } from "react"

export default function App() {
  const [isOpen, setIsOpen] = useState(false)

  return (
    <div style={{ padding: 16 }}>
      <button onClick={() => setIsOpen(!isOpen)}>
        {isOpen ? "Close" : "Open"}
      </button>
      {isOpen && <p>This shows only when it is open</p>}
    </div>
  )
}
  1. Make the text shown when open two lines long
  2. Show "Closed" only when it's closed (hint: !isOpen &&)
  3. Make it start out open (hint: the initial value of useState)

Common pitfalls

Using a number as the && condition shows "0"
With {count && <p>…</p>}, when count is 0, a 0 appears on the screen. For numbers, write {count > 0 && …}.
!isOpen means "the opposite of isOpen"
! flips true and false. setIsOpen(!isOpen) means "make it the opposite of now" — the standard way to toggle open and closed.