liveBook · Manning

Conditional logic

As explained in React Quickly, Second Edition

An if/else statement conditionally executes one of two statement branches based on a Boolean expression.

Conditional logic chooses which JSX a React component renders. Because JSX is JavaScript, components can use familiar conditions while following patterns suited to rendering interfaces. section 3.2.6 section 3.7

Choose the pattern that matches the branching job:

  • Return early when the component should render nothing, usually by returning null before unnecessary calculations or JSX creation. section 3.2.6
  • Use the ternary operator when a condition selects between two alternative elements, such as an empty or populated shopping cart. section 3.2.6
  • Use the logical AND operator for optional elements, such as displaying a verification checkmark only for verified users. section 3.2.6
  • Use object maps for several alternatives and separate components when the branching becomes complex. section 3.2.6

A countdown that disappears at zero

Check the stopping condition first, return null when no countdown remains, and calculate minutes and seconds only for visible output. section 3.2.6

How React Quickly, Second Edition covers it

How deep it goes
Explains early returns, ternaries, logical AND, object maps, and component decomposition without descending into JavaScript or React internals.
Examples
Uses countdowns, online status, shopping carts, verified usernames, post-status icons, and nested cart controls.
What it assumes
Builds on JavaScript expressions and truthiness while treating JSX as JavaScript that must eventually be transpiled.
What you can do after
Apply it via JSX to render alternatives, optional elements, empty states, and nothing when conditions require.
How it connects
Connects conditional logic to JSX, React components, ternary operators, logical operators, early returns, and object maps.

Also explained in

Compare how 21 books explain conditional logic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.