- Home
- Javascript
- Conditional Rendering
Conditional Rendering
Contents
Conditional Rendering
Conditional rendering with the ternary operator lets you display different content based on a condition in a concise, clean way. It works like: condition? valueIfTrue: valueIfFalse, meaning if the condition is true, one value is shown; otherwise, another value is displayed.
<p className="text-base md:text-xl p-2 lg:p-3">
Your age is:{" "}
{dob
? (() => {
const { years, months } = calculateAge(dob);
if (years === 0) return `${months} months`;
if (months === 0) return `${years} years`;
return `${years} years ${months} months`;
})()
: ""}
</p>Explanation:
In this code, a ternary operator checks whether dob is selected; if it is, an immediately invoked function runs, calls calculateAge(dob), and returns the formatted age (only months, only years, or both). If dob is not selected, it renders an empty string, so nothing is shown.
Whenever the dob changes, React re-renders the component; the function runs again, and the updated age is displayed inside the <p> (paragraph) tag.










