Code Snippets
/

React Conditional Rendering Patterns

React Conditional Rendering Patterns

Conditional rendering in React looks easy until the `0`-falsy-render bug ships to production. This snippet covers the three patterns you should reach for in order: a ternary in JSX for either-or branches, the `&&` short-circuit (with the famous `0` gotcha and its fix), and an early-return plus extracted helper component when the branching gets dense. Examples render a small text representation of the output so the teaching is independent of any JSX compiler.

JavaScript
Easy
3 snippets
react
hooks
conditionals

806 views

25

// Standalone JS demo. In real React the bodies would be JSX; we use a tiny
// `el(tag, children)` helper that mimics what React.createElement would produce
// and a `render(node)` that turns the node tree into a printable string.
function el(tag, children) { return { tag, children }; }
function render(node) {
    if (node === null || node === undefined || node === false) return '';
    if (typeof node === 'string' || typeof node === 'number') return String(node);
    const inner = (node.children || []).map(render).join('');
    return `<${node.tag}>${inner}</${node.tag}>`;
}

// Welcome banner that flips between two messages based on isLoggedIn.
function Welcome({ isLoggedIn, name }) {
    return el('div', [
        isLoggedIn
            ? el('span', ['Welcome back, ', name, '!'])
            : el('a', ['Sign in']),
    ]);
}

console.log(render(Welcome({ isLoggedIn: true, name: 'Ada' })));
// <div><span>Welcome back, Ada!</span></div>
console.log(render(Welcome({ isLoggedIn: false, name: 'Ada' })));
// <div><a>Sign in</a></div>

// Returning null is React's way to render nothing without breaking the tree.
function Banner({ message }) {
    return message ? el('div', [message]) : null;
}
console.log(render(Banner({ message: '' })));
// (empty string)
console.log(render(Banner({ message: 'Hello' })));
// <div>Hello</div>

A ternary in JSX is the cleanest way to express "either A or B": both branches are explicit, and the result is always a valid React node. When you want "render this only sometimes", returning null (or false, or undefined) tells React to render nothing, which is safer than building an empty <div>. The el/render pair here mimics what React.createElement and the renderer do under the hood so we can run the example in plain Node; in your real component you would write <span>Welcome back, {name}!</span> instead. Keep ternaries short; nested ternaries hurt readability fast and should be refactored to early returns or a helper component.