Document how to apply a `class` to an Astro component
I've already seen multiple support issues where new Astro developers are struggling with getting syntax like this to work:
<SomeAstroComponent class="some-css-class">
...
</SomeAstroComponent>
The challenge is how to get class to be rendered in the HTML output.
This is a typical use case and it's unfortunately also a bit special due to class being seen as a reserved name in JS.
This does not work inside the component frontmatter:
const { class } = Astro.props
You need to rename the property to get it to work, and then use the renamed property in the root element of the component template:
const { class: className } = Astro.props
We should probably document this in an example.
Good idea! Maybe something for the Styling & CSS page?
Good idea! Maybe something for the Styling & CSS page?
Yes, either that, or on the Components page, where there even is a CSS Styles example: https://docs.astro.build/en/core-concepts/astro-components/#css-styles
CSS Styles definitely need iteration.
I'm seeing numerous threads about using the same component twice, and passing in define:vars to the <style> tags overwrites them in the separate components.
This issue is however feels more like a Components/Dynamic Attributes than styling.
At the same time, I wouldn't entirely ditch automating the expected behaviour in some way. If the component consists of a single HTML Tag, it is valid and could be expected to pass the class to that single tag without having to write props and JSX. This is something that probably @natemoo-re could elaborate on, if it's easy/worth to implement. For other use-cases, manually passing in classes feels the way to go.
At the same time, if there is a consensus, I'll gladly update the documentation!
A documentation PR would be great! Even if some kind of automated passing ever comes to pass, I bet it could be a while — sounds like something that would need an RFC given all the complexities — so docs in the meantime would be super helpful. Thanks @lostra01!
I'll ping @sarah11918 here as well, and if everything's in line I'll keep in touch with her throughout the process.
Discussed this on our v1 triage call. Some ideas of where this could go: maybe the troubleshooting page or a future “migration from other frameworks” page?
Not quite sure what’s best — need to think if people need to be presented this while learning or more something they’ll search for if it comes up while working.
There’s some helpful content in #1011 someone might want to pick up and use!