#Passing class to component.

5 messages · Page 1 of 1 (latest)

rough sparrow
#

I want to style my custom .astro component by passing classes. When I follow the official documents and do

interface Props {
  className?: Class;
}

const { className, ...rest } = Astro.props;

it gives an error saying "Cannot find name 'class'".

How do I pass classes/styles to my astro component using typescript?

short streamBOT
#

Hi @rough sparrow. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, HTML attributes like class do not automatically pass through to child components. Instead, you should accept a class prop in the child component and apply it to the root element. However, when destructuring, you must rename it, because class is a reserved word in JavaScript.

Here's how you can do it:

---const { class: className, ...rest } = Astro.props;---
<div class={className} {...rest}>  
  <slot/>
</div>

In the above code, class is renamed to className when destructuring Astro.props.

Then, you can pass the class to your component like this:

---import MyComponent from "../components/MyComponent.astro"---
<style>  
  .red {    
    color: red;  
  }
</style>
<MyComponent class="red">This will be red!</MyComponent>

In the above code, MyComponent is being passed a class of red.

For TypeScript support, you can define your props with a Props type interface. Astro will automatically pick up the Props interface in your frontmatter and give type warnings/errors. Here's how you can do it:

---interface Props {  
  class?: string;
}
const { class: className = "" } = Astro.props as Props;---
<div class={className}>  
  <slot/>
</div>

In the above code, Props interface is defined with an optional class property of type string. Then, class is renamed to className when destructuring Astro.props and it's also given a default value of an empty string.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@rough sparrow kapa.ai is still learning and improving, please let us know how it did by reacting below

rough sparrow
#

That worked