Introduction
While building an app with React and Supabase,
I encountered a situation where I wanted to display a link only under certain conditions.
At first, I was using if/else, but then I remembered the ternary operator (?:).
I'd like to recap the ternary operator (?:).
What is the ternary operator?
The syntax is simple:
Condition ? True : False
Example: GitHub URL case analysis
Standard if/else
let githubUrl;
if (user.github_id) {
githubUrl = `https://github.com/${user.github_id}`;
} else {
githubUrl = null;
}
Using the ternary operator...
const githubUrl = user.github_id
? `https://github.com/${user.github_id}`
: null;
Useful in JSX
The ternary operator is also useful for toggling visibility.
{githubUrl ? (
<a href={githubUrl} target="_blank">GitHub</a>
) : (
<p>Not registered</p>
)}
Summary
I had forgotten some grammar, so I'd like to review it again.
Top comments (0)