Chapter 3 of 4

Conditional Styling and Remounting

Toggling classes, and how keys decide whether React reuses or rebuilds an element.

Conditional classes are just string expressions. For anything beyond one or two toggles, a helper such as classnames keeps it readable.

<button className={isActive ? "tab tab-active" : "tab"}>Overview</button>

// With a helper
<button className={classNames("tab", { "tab-active": isActive })}>
  Overview
</button>

Conditionals change what React reuses

React matches elements between renders by position and type. If the type at a position is the same, React reuses the existing DOM node and its state. If it differs, it destroys the old one and builds a new one.

// Same type at the same position: the input keeps its value
{isEditing ? <input className="edit" /> : <input className="view" />}

// Different type: the DOM node is thrown away and rebuilt
{isEditing ? <input /> : <textarea />}

Forcing a reset with key

Sometimes resetting is exactly what you want - for example, clearing a form when the selected record changes. Give the element a key that changes, and React rebuilds it with fresh state.

// Each time userId changes, the form remounts with empty state
<ProfileForm key={userId} userId={userId} />

Choose a status label

Complete statusLabel so it returns 'Online' for true, 'Offline' for false, and 'Unknown' when the value is undefined or null.

Toggle a panel open and closed

Wire the button so clicking it toggles the paragraph. When open, the paragraph with id 'panel' should exist; when closed, it should not.