🎓 A1Learner
🔍
0 of 50 lessons completed

Logical AND Rendering

Logical AND rendering shows content only when a condition is true. The double ampersand joins the condition and the content.

A message that sometimes shows

The message shows because hasMail is true.

const hasMail = true;
return <div>{hasMail && <p>Mail arrived.</p>}</div>;

Nothing when false

The div stays empty because hasMail is false.

const hasMail = false;
return <div>{hasMail && <p>Mail arrived.</p>}</div>;

Example

import { useState } from 'react';

export default function App() {
  const [show, setShow] = useState(false);
  return (
    <div>
      <button onClick={() => setShow(!show)}>Toggle help</button>
      {show && <p>Help is here.</p>}
    </div>
  );
}

Key points

  • The double ampersand is the logical AND operator.
  • The content after it renders only when the condition is true.
  • Nothing renders when the condition is false.
  • The pattern suits a message that sometimes appears.

In this example, the show state value starts as false. The button flips show with each click. The paragraph renders only when show is true. The first render shows the button alone.

Note

A zero count renders as the number zero, so compare the count with zero first.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What renders when show is false in {show && <p>Help.</p>}?