I've got a bunch of web components built where a consumer may be consuming one or many of these components.
They are used by adding a script
tag to the components minified JS and then using the web component in your code like so: <my-cool-component data="someData" />
.
CSS is built into these components, however, I need to add functionality to allow the consumers to customize the color theme, and I'm wondering if my approach here could be improved, or if there is a better approach all together.
Right now I have it setup so that when someone consumes any of the components, like my-cool-component
and they have a window.coolComponentOptions
set like this:
window.coolComponentOptions = {
PRIMARY_BUTTON_BACKGROUND_COLOR: 'tomato',
PRIMARY_BUTTON_COLOR: '#fff',
URL_COLOR: 'tomato',
FONT: 'Arial',
SECONDARY_BUTTON_BACKGROUND_COLOR: 'lightblue',
... // Obviously this could grow tremendously
}
I do a check inside of my-cool-component
and see if the coolComponentOptions
exist and if so I map them to the CSS variables and use them inside of any of the components.
Alternatively I could make these values props on the component itself like <my-cool-component primary-btn-color="tomato" />
but this could cause the consumer to have an element with tons of attributes, and when they consume <other-cool-comp />
they will need to repeat these attributes again.
I'm curious if there are any other (better) options than the way I am doing it with the window
variable, or if that approach could be improved upon or is completely acceptable?
CSS variables can be global CSS definitions.
And shadowParts give you even more global CSS / shadowDOM styling.
Very good explainer by Monica Dinculescu, former Google Web Components team member
https://meowni.ca/posts/part-theme-explainer/