Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Astro JS if statement

Tags:

astrojs

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

like image 647
alexyon Avatar asked May 19 '26 21:05

alexyon


2 Answers

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>
like image 98
Stratis Dermanoutsos Avatar answered May 22 '26 16:05

Stratis Dermanoutsos


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>
like image 44
Gianfranco P. Avatar answered May 22 '26 18:05

Gianfranco P.