Astro - If Else Statements
Basic
With a true
or false
statement, we can simply create something like a link or button that changes depending on if the user is signed in.
Let's start out this example:
---
var UserLogin = false
---
{UserLogin ?
<a>Log Out</a>
:
<a>Sign in</a>
}
Since the example above has it's variable set to false
, this would show the "Sign In" button as a result.
Custom Variable
If you're not using the basic true
/false
strings for your variable and are using a custom variable instead as you may have more than just two conditions to handle. We can check if the variable matches a string instead.
Here's an example:
---
const AccountType = "external"
---
{
()=> {
if (UserLogin === "external") {
return <p>Account Type: External</p>
} else if (AccountType === "local") {
return <p>Account Type: Local</p>
} else {
return <p>Account Type: Unknown</p>
}
}
}
Array Includes
Just like the custom variable section, we can use mostly the same way to check if an item is included with an array.
Create an array, for example:
var Badges = ["Admin", "Moderator", "Premium"]
Then, check if the item exist in that array with the includes
function:
{()=> {if (Badges.includes("Admin")) {return <p>Admin</p>}}}
Full example:
---
var Badges = ["Admin", "Moderator", "Premium"]
---
<div class="user-badges">
{()=> {if (Badges.includes("Admin")) {return <p>Admin</p>}}}
{()=> {if (Badges.includes("Moderator")) {return <p>Moderator</p>}}}
{()=> {if (Badges.includes("Premium")) {return <p>Premium</p>}}}
{()=> {if (Badges.includes("Newcomer")) {return <p>Newcomer</p>}}}
</div>