I need to create a button component that can have different colours. I would like, when using the component, to be able to specify as prop a colour e.g. "#ff0000", but also my SCSS variable e.g. "$primary". However, I know that it is not possible to do something like this because SCSS variables are processed at application build stage and not at runtime.
I am currently using this solution. It allows to set the colour of $primary
when primary
is passed as prop. However, this only works for one variable - it is not possible to do something like this for both $primary
and $secondary
.
<script> export let fill; $: formattedFill = fill === 'primary' ? '' : fill;</script><button style="--fill: {formattedFill}"><slot/></button><style lang="scss"> button{ background-color: var(--fill, $primary) }</style>
Of course, I can create an object e.g.
const colors = { primary: "#00ff00", secondary: "#0000ff" }
and then refer to it with the value passed in the props. However, for me this solution is silly - I want centralised colour variables, not scattered in several files.