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
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With