Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use props when passing data to custom elements (#875) #1636

Merged
merged 2 commits into from
Aug 8, 2018
Merged

Conversation

Rich-Harris
Copy link
Member

This changes the behaviour of attributes on custom elements — previously, data would always be passed to custom elements using setAttribute, which only works for strings.

Now, it uses a simple heuristic: if the prop exists on the custom element, it is set as a prop, otherwise it's an attribute. (This is similar to what Preact does.)

So in this case...

<fancy-list items={things}/>

...as long as items is the name of a property on a FancyList instance (whether or not it had previously been set), the value of items inside the component will be an array rather than the dreaded "[object Object]".

Typically, custom elements use accessors for properties that their consumers should be able to read and write...

class FancyList extends HTMLElement {
  ...
  get items() {
    // ...
  }

  set items(items) {
    // ...
  }
}

...and that's similar to the code Svelte generates for custom elements, so this ought to be a reliable heuristic. Meanwhile, unexpected props still become attributes, allowing this sort of thing:

<fancy-list style="font-family: 'Comic Sans MS'" items={things}/>

With this PR, we pass all the tests on https://custom-elements-everywhere.com

screen shot 2018-08-05 at 1 55 22 pm

— which is better than React, Preact, and, err... Polymer, the custom element framework 😳

@Rich-Harris Rich-Harris merged commit 2880428 into master Aug 8, 2018
@Rich-Harris Rich-Harris deleted the gh-875 branch August 8, 2018 12:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant