javascriptconditional-statementsastrojsmdxjs

Astro component how to render div based on prop value


I'm new to javascript in general and learning Astro. I couldn't figure out what's wrong with this conditional? The site builds but it's not finding matches and always ends in "unknown kind". If there's a better way to do this please let me know. Below is the astro component and I'm using Astro with typescript, calling the component in an MDX file.

// Component.astro

---
const { kind } = Astro.props;
---

{
  () => {
    if (kind === "a") {
      <div>a</div>
    }
    if (kind === "b") {
      <div>b</div>    
    }
    if (kind === "c") {
      <div>c</div>
    } else {
      console.log("unknown kind.");
    }
  }
}

// the MDX file

<Component kind="a" />

I also felt there should be a simpler short hand to write these statements. But I can't even get the verbose version working. Appreciate any help.


Solution

  • Working example

    It's about how the compiler works, here's your example reworked

    // Component.astro
    
    ---
    const { kind } = Astro.props;
    //ensure kind is 'other' in fallback case
    ---
    
    {(kind === "a") &&
          <div>a</div>
    }
    {(kind === "b") &&
          <div>b</div>    
    }
    {(kind === "c") &&
          <div>c</div>
    }
    {(kind === "other") &&
          console.log("unknown kind.");
    }
    

    Reference

    https://docs.astro.build/en/core-concepts/astro-syntax/#dynamic-html