Don't get me wrong, I have nothing against default values for web component APIs. The problem I have with them is that they are unreliable.
The Problem
A common approach for providing a list of available options for an API is using TypeScript's untion type.
/** The display variant for the button */
@property({reflect: true})
variant: 'default' | 'solid' | 'ghost' = 'default';
Here is some basic CSS to make the variations work.
:host {
--accent-color: #0265dc;
}
button {
cursor: pointer;
padding: 0.5rem;
}
:host([variant='default']) button {
border: solid 1px var(--accent-color);
background-color: white;
color: var(--accent-color);
}
:host([variant='solid']) button {
border: solid 1px var(--accent-color);
background-color: var(--accent-color);
color: white;
}
:host([variant='ghost']) button {
border: solid 1px transparent;
background-color: transparent;
color: var(--accent-color);
}
NOTE: The code examples are using
- Unset
- without an attribute set it works fine because we have a default value and it is configured to reflect the attribute on the element when it is set.
- if we set the
variantproperty toundefined, it breaks the styles.
CODE<!-- No attribute set -->
<my-button>No Attribute Button</my-button>
<!-- JSX example -->
<my-button variant={undefined}>Unset Button</my-button>
You can test this example here:
You can see the final code here:
to create web components that work consistently.
↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
SOCIAL SHARE CARD GENERATOR