htmlcsstailwind-cssastrojs

Can I pass additional classes to an Astro component from parent?


I'm working with an Astro component that already has some classes in its template. I'm looking to reuse this component in a different view to alter the color of its header exclusively for that view.

According to the documentation, passing a class prop makes adding classes from a parent to a child possible. However, I'm finding it challenging to retain the existing classes in the component while overriding or adding another class.

<ExpansionQuestion question={question.question}>
  <Fragment slot="body" set:html={question.answer} />
</ExpansionQuestion>

ExpansionQuestion root element:

<details class="group bg-blue-gray duration-300 rounded-lg p-4 w-full shadow-md focus:outline-none focus:ring-0">

My goal is to add a bg-secondary class to the details element in one specific view while ensuring the rest of the classes remain unchanged across all views.

Is it possible to do this?


Solution

  • One approach here is to use Astro’s class:list directive. This lets you combine various classes more easily.

    In your example, you might do something like this:

    1. Pass the additional class to the component where you use it (here using a bg prop, but you could adapt this for whatever situation):

      <ExpansionQuestion question={question.question} bg="bg-secondary">
        <Fragment slot="body" set:html={question.answer} />
      </ExpansionQuestion>
      
    2. Use the prop to control the background in the ExpansionQuestion.astro component:

      ---
      const { bg } = Astro.props;
      ---
      <details
        class:list={[
          "group duration-300 rounded-lg p-4 w-full",
          "shadow-md focus:outline-none focus:ring-0",
          bg || "bg-blue-gray"
        ]}
      >
      

      Astro will automatically combine the items in the class:list array, and in this case will use the bg prop if it is passed, but will default to the blue gray colour if no prop was passed.