Reputation: 83
How could i put a condition in a component astro JS. for example, how could i display a item if only is "DOG" ?
---
const items = ["Dog", "Cat", "Platypus"];
---
<ul>
{items.map((item) => (
<li>{item}</li>
))}
</ul>
https://docs.astro.build/en/core-concepts/astro-components/#dynamic-html
Upvotes: 8
Views: 12346
Reputation: 10794
You could also filter it in the section above – called Component Script (JavaScript)
– and create a new variable so it's easier to read.
---
const items = ["Dog", "Cat", "Platypus"];
const onlyDogs = items.filter(item => item === "Dog");
---
<ul>
{onlyDogs.map((item) => (
<li>{item}</li>
))}
</ul>
Upvotes: 3
Reputation: 787
You could use the JS's filter method on the array to only use the items that apply to your condition.
---
const items = ["Dog", "Cat", "Platypus"];
---
<ul>
{items.filter(item => item === "Dog").map(item => (
<li>{item}</li>
))}
</ul>
Another way would be to use nested conditional rendering, which is not ideal nor very appealing to the eye.
---
const items = ["Dog", "Cat", "Platypus"];
---
<ul>
{items.map(item => (
{item === "Dog" && <li>{item}</li>}
))}
</ul>
Upvotes: 7