function MyComponent(props) { const { headerCopy } = props; return <div>{headerCopy && <h1>{headerCopy}</h1>}</div>;}headerCopy is equal to 0?function MyComponent(props) { const headerCopy = 0; return <div>{headerCopy && <em>{headerCopy}</em>}</div>;}0 is a false-y value and not one that React specifically ignores, you'll run into the "short-circuit" effect of this pattern– a zero will be rendered instead of nothing, which is likely what you would have wanted in this case.typeof, undefined, or a Boolean. So, in this instance, you have a few options.Boolean is one of the types that React knows not the render, we can explicitly cast our value as a Boolean :function MyComponent(props) { const { headerCopy } = props; return <div>{Boolean(headerCopy) && <em>{headerCopy}</em>}</div>;}Boolean(headerCopy) will still evaluate to true but React knows not to render it.Boolean. If you're familiar with logical operators, you know that prefixing a value with a Bang (!) operator reverses the value of it. The only way to do this is to cast it as a Boolean, so JavaScript does that for you. The SECOND Bang flips it back to it's original truth-y/false-y value while keeping it casted as a Boolean. Confused? That's normal! Let's look at some examples:!true; // Evaluates to false!false; // Evaluates to true!'Hello'; // Evaluates to false!''; // Evaluates to true// The DOUBLE BANG!!!true; // Evaluates to true!!!false; // Evaluates to false!!!'Hello'; // Evaluates to true!!!''; // Evaluates to false!!!0 would evaluate to? If you guessed false, you're right! Since 0 is false-y, and we're casting it, reversing it, and then flipping it back, it evaluates to it's associated Boolean value. So, how do we use that as a replacement to fix our short-circuit evaluations? Like this:function MyComponent(props) { const { headerCopy } = props; return <div>{!!headerCopy && <em>{headerCopy}</em>}</div>;}function MyComponent(props) { const { headerCopy } = props; return ( <div> {headerCopy ? <em>{headerCopy}</em> : <strong>N/A</strong>} </div> );}null and React will ignore it:function MyComponent(props) { const { headerCopy } = props; return <div>{headerCopy ? <em>{headerCopy}</em> : null}</div>;}Posted Feb 22, 2023
A common pattern in React can sometimes get a little hairy. Let's learn the ins-and-outs of this pattern.
0
24