#Unnable to change css when calling a small component

2 messages · Page 1 of 1 (latest)

zealous sinew
#

Im trying to create a functionality that will allow me to change css clases when calling a small reusable component.
I tried applying the changes into tailwind classes and inside the style tag, but without any succes.
How can i achive that?

This is my file StandardGreenButton.astro:

---
const { bgColor } = Astro.props
---
<button type="button" class="transition ease-in-out delay-50 duration-[900ms] text-secondary-shade bg-primary-shade border-2 border-primary-shade shadow-md hover:bg-primary-tint hover:text-primary-contrastShade hover:shadow-lg hover:border-primary-shade focus:outline-none focus:ring-2 focus:ring-primary-shade focus:text-black font-medium rounded-lg text-base px-5 py-2.5 mr-2 mb-2 h-14">Comece a empreender</button>

<style>
    button { background-color: bgColor }
</style>

But if i call this component like

<StandardGreenButton bgColor="red"></StandardGreenButton>

It doesnt apply any changes

solar chasm
# zealous sinew Im trying to create a functionality that will allow me to change css clases when...

You can use the define:vars directive to pass frontmatter variables to your <style> tag. https://docs.astro.build/en/reference/directives-reference/#definevars
BUT define:vars will disable scoping and inline the style tag meaning this style could leak to any other button on the page

To get around this you can use a style attribute instead: ```jsx

const {
bgColor
} = Astro.props

<button
type="button"
style={--bg:${bgColor};}
class:list={[
"transition ease-in-out delay-50 duration-[900ms] text-secondary-shade border-2 border-primary-shade shadow-md hover:bg-primary-tint hover:text-primary-contrastShade hover:shadow-lg hover:border-primary-shade focus:outline-none focus:ring-2 focus:ring-primary-shade focus:text-black font-medium rounded-lg text-base px-5 py-2.5 mr-2 mb-2 h-14",
bgColor
? "bg-[var(--bg)]"
: "bg-primary-shade"
]}

Comece a empreender
</button>