Hacker News new | ask | show | jobs
by jjcm 1874 days ago
Super easy to incorporate with React. Just use react to pass attributes, like so:

    class App extends React.Component {
      render() {
        return (
          <my-component custom-attribute={value}></my-component>
        )
      }
    }
In your webcomponent just make sure you listen to changes to that attribute like so:

    static get observedAttributes() {
      return ['custom-attribute']
    }
Then you can decide how the component changes whenever that attribute is updated by using the `attributeChangedCallback` function. Alternatively, use a base element that incorporates a render() function which will automatically update everything in the shadowdom.

Main difference is it becomes much harder to pass complex data structures. Passing strings is easy, but passing an array of data isn't feasible with this model.

1 comments

Issues arise when trying to pass objects or add event listeners for custom events due to how React specifically handles this stuff. You often have to use refs
And even refs aren't enough if the custom element does its initial render asynchronously. I had to add mutation observers to some wrappers to avoid polling the ref.current.