preactjs / preact-custom-element

Wrap your component up as a custom element
MIT License
360 stars 52 forks source link

Pass context value across custom element boundary #43

Closed marvinhagemeister closed 4 years ago

marvinhagemeister commented 4 years ago

This PR adds support for passing Preact's context value to other custom elements that are rendered with Preact further down the tree. Take this example where we have two Preact components converted to a web component to pass a theme value around:

<x-theme-provider theme="light">
  <x-display-theme />
</x-theme-provider>

There we want the inner node to receive any updates to the provider's context value. Problem is that due to the custom element boundaries we are not part of Preact's render function and need to pull the context value from any parents ourselves.

For updates we're already set once context is set up, because the createContext-API holds a direct reference to the child consumers. So we only need to pull the context ourselves during the mount phase.

Fixes #40 .