Search code examples
astrojs

Astro JS if statement


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


Solution

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