Rendering and data flow
Render a condition
Use normal JavaScript to choose which JSX a component returns.
Use ordinary JavaScript conditions to choose JSX.
Return early when the whole screen state changes:
function Account({ user }) {
if (!user) {
return <LoginForm />
}
return <Dashboard user={user} />
}
Use a ternary for two small alternatives:
<p>{saved ? 'Saved' : 'Unsaved changes'}</p>
Use && when the false branch should render nothing:
{error && <p role="alert">{error}</p>}
Be careful with numbers. items.length && <List /> renders 0 for an empty list. Write items.length > 0 && <List /> when that is the real condition.
Do not hide inaccessible markup with CSS when it should not exist in the interaction tree. Conditional rendering can remove it from both the DOM and accessibility tree.
Avoid deeply nested ternaries. Calculate a named variable or extract a component when the states become hard to scan.
Render loading, error, empty, and success states for one list. Make each state explicit and reachable in a test.
Lesson completed