Sometimes, we want to use ternary operator in JSX to include HTML with React.
In this article, we’ll look at how to use ternary operator in JSX to include HTML with React.
How to use ternary operator in JSX to include HTML with React?
To use ternary operator in JSX to include HTML with React, we use JSX code as expressions for the ternary operator’s operands.
For instance, we write
const Comp = () => {
//...
return (
<div className="row">
{message === "failed" ? (
<div> Something went wrong </div>
) : (
<div> Everything is fine </div>
)}
</div>
);
};
to if message
is 'failed'
.
If it is, then we render <div> Something went wrong </div>
.
Otherwise, we render <div> Everything is fine </div>
.
Conclusion
To use ternary operator in JSX to include HTML with React, we use JSX code as expressions for the ternary operator’s operands.