1

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

alexyon
  • 13
  • 1
  • 4

2 Answers2

3

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>
1

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>
Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68