Nullish coalescing with React and TypeScript
The last post went through how we can use optional chaining in React and TypeScript apps to shorten our code. Nullish coalescing is another excellent new JavaScript feature that helps us improve our React and TypeScript apps. Let’s find out what this feature is and how it’s useful in React and TypeScript apps.
A simple component
Let’s start with a simple component:
type Person = {
name: string,
subscription?: Subscription
};
type Subscription = {
amount: number
};
type Props = {
person: Person
};
const PersonCard: React.FC<Props> = ({
person
}) => {
return (
<div>
<div>
<span>Name: </span>
<span>{person.name}</span>
</div>
<div>
<span>Subscription amount: </span>
<span>
{person.subscription?.amount} </span>
</div>
</div>
);
};
We are using optional chaining on the highlighted line so that we don’t get an error when rendering the subscription amount. However, let’s say we want to render “No subscription” if the person has no subscription. We may use something like this:
<span>
{person.subscription?.amount ||
"No subscription"}
</span>
However, what if the person has a subscription, but it is free? - i.e. person.subscription.amount
is 0
. In this case, “No subscription” would be rendered because 0
is a falsy value.
Using nullish coalescing
A nullish coalescing approach looks very similar:
<span>
{person.subscription?.amount ??
"No subscription"}
</span>
Notice the nullish coalescing operator (??
). This renders the right-hand operand if the left-hand operand is null
or undefined
. So, it’s more precise than ||
and does precisely want we want in our case, resolving the free subscription bug.
Can I use nullish coalescing now?
Yes, if you are running recent versions of React and TypeScript:
- TypeScript 3.7 supports nullish coalescing
- Babel 7.8.0 supports nullish coalescing
- Projects created with create react app 3.3.0 supports nullish coalescing as well!
Did you find this post useful?
Let me know by sharing it on Twitter.If you to learn more about using TypeScript with React, you may find my course useful: