0% completed
Another popular and clean way to conditionally render component is through the use of ternary operators. A ternary operator is a shorthand for an if-else statement.
The ? stands for if and the : stands for else.
Syntax
condition ? expression_if_true : expression_if_false
The ternary operator can be used within JSX to conditionally render different UI elements based on certain conditions.
Using the user login example in the previous lesson, we can convert the code to conditionally render using ternaries:
function App() { const isUserLoggedIn = true; return ( <div> <h1>React Course</h1> {isUserLoggedIn ? <p>Welcome back!</p> : <p>Please log in</p>} </div> ); }
In this example:
You can also use ternary operators to conditionally render entire components. For instance, you may want to show different components based on whether a user is an admin or a regular user.
function AdminPanel() { return <div>Admin Panel</div>; } function UserPanel() { return <div>User Panel</div>; } export default function Dashboard({ user }) { return ( <div> {user.isAdmin ? <AdminPanel /> : <UserPanel />} </div> ); }
In this example, the AdminPanel component is rendered if user.isAdmin
is true; otherwise, the UserPanel component is rendered, returning their respective JSX.
.....
.....
.....