liveBook · Manning

Branch

As explained in React Quickly, Second Edition

Branching is the selection of different program paths or outputs according to conditions.

Branching selects different UI paths or outputs according to conditions. In JSX, use familiar JavaScript constructs to decide what a React component renders. section 3.2.6

Choose a pattern based on the rendering decision:

  • Return null early when the component should render nothing. section 3.2.6
  • Use a ternary operator for two alternative elements, such as online versus offline status or an empty versus populated cart. section 3.2.6
  • Use && for optional elements, such as a verification checkmark or an address-dependent button. section 3.2.6
  • Use object maps for several named alternatives, and split complex conditions into extra components. section 3.2.6

Shopping cart decisions

A cart can branch on login state, payment details, shipping address, item availability, and whether it contains items. Separate UserButtons and GuestButtons components make those conditions easier to follow than one deeply nested render. section 3.2.6

class Countdown extends Component {
 render() {
   if (this.props.remaining === 0) {
     return null;
   }
   const seconds = this.props.remaining % 60;
   const minutes = Math.floor(this.props.remaining / 60);
   return <p>{minutes}:{seconds}</p>;
 }
}

The early-return Countdown implementation checks whether time remains before calculating display values or creating JSX. section 3.2.6

How React Quickly, Second Edition covers it

How deep it goes
Explains five JSX branching patterns with runnable component examples, stopping short of broader control-flow theory.
Examples
Demonstrates countdowns, online status, shopping carts, verification marks, post icons, and split cart components.
What it assumes
Uses JavaScript conditional constructs through JSX without establishing additional conceptual prerequisites.
What you can do after
Apply it via React and JSX to render nothing, alternatives, optional elements, mapped states, and complex component branches.
How it connects
Connects branching with JSX, React components, ternary operators, logical AND, early returns, and object maps.

Also explained in

Compare how 6 books explain branch →

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.