#Passing class to component.
5 messages · Page 1 of 1 (latest)
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:
- Passing a
classto a child component (https://docs.astro.build/en/guides/styling/#passing-a-class-to-a-child-component) - Component Props (https://docs.astro.build/en/guides/typescript/#component-props)
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
That worked