preact-custom-element
preact-custom-element copied to clipboard
Parse attributes from custom element
I want to pass attribs in my custom element like this:
<my-custom-element attribute-one="[1,2,3,4]" ></my-custom-element>
and receive that into my preact component as an Array, and not a String. For now, im parsing all my props before rendering:
for(let key in this.props){
try {
this.props[key] = JSON.parse(this.props[key])
} catch (e) {}
}
Do you guys think that is a nice improvement for the project? If you agree, i can make a PR with that, just let me know!
One option here would be to add a hint in the property name - something like <c-e prop$="[1,2,3">
I implemented some fairly simple logic for this in my org's forked vue wc wrapper around here, where users would pass a JSON to a prop with a -json suffix, then map that -json back to the "real" prop. It helped us keep the seamlessness between consuming components as Web Components or just as plain Vue components.
For clarity:
<x-element something-json="[1,2,3]">...</x-element>
Would get mapped to something
inside the component, Array.isArray(something)
would evaluate to true
.