This content originally appeared on Go Make Things and was authored by Go Make Things
One of my favorite ways to customize Web Components is with custom attributes.
Since writing that last article, I’ve gotten some questions around using custom attributes in Web Components, and I’ve also see their popularity increase a fair bit.
Let’s talk about some caveats and things to know.
Why custom attributes?
Probably the most common question I get is why use a custom attribute instead of [data-*]
attributes?
Personally, I think it provides a nicer authoring experience. Prefixing every customization with data-*
can get really cumbersome. Being about to write things like target="#password"
or group="true"
is a lot simpler, especially if your options are more complex.
This is, of course, entirely subjective!
Linters won’t like them
HTML linters will typically tell you that custom attributes are invalid.
Every single browser I’ve used handles them just fine, and you can get, set, and update them with JavaScript just like you would any other attribute.
If having a completely error and warning free linting experience is your end goal, don’t use custom attributes. Otherwise, they’ll work just fine despite what the linter says.
You could run into future collisions
Perhaps the biggest danger of custom attributes is that a future update to the web platform adds an attribute whose name is the same as one you’ve used in your Web Components.
For example, if [target]
ever becomes a standard attribute, any Web Component using it as a custom one could see some unexpected collisions and behaviors.
One way to reduce the likelihood of this is to always use hyphenated attributes (in the same way custom elements must always have a dash).
I sometimes use things like [wc-*]
or the name of the component itself.
This can erode the benefits of using custom attributes traditional data attributes, but it can also make it more clear which attributes are specific to your Web Component.
🎉 New Year Sale! Now through the New Year, get 40% off your first year of Lean Web Club membership. Level-up as a developer. Click here to learn more.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2025-01-03T14:30:00+00:00) Custom attributes in Web Components. Retrieved from https://www.scien.cx/2025/01/03/custom-attributes-in-web-components/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.