preactjs / preact-custom-element

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

Observed attributes break context providers #65

Open Rkaede opened 2 years ago

Rkaede commented 2 years ago

When a custom element has an observed attribute, a context provider will not take a value.

const ThemeContext = createContext('light');

function Theme({ children, theme = 'dark' }) {
  // We can read the value being passed in:
  console.log(theme); // 'dark'

  // But the provider below will not set its value to 'dark'.
  //
  // Any children using the context will get 'light'.
  //
  // Even if we passed in a value directly:
  // <ThemeContext.Provider value={'blue'}>
  // the children will still get 'light'.
  return (
    <ThemeContext.Provider value={theme}>
      <div>{children}</div>
    </ThemeContext.Provider>
  );
}

// Removing the "theme" attribute below resolves the issue. The context will then take a value.
registerElement(Theme, 'x-theme', ['theme'], { shadow: true });

Full working example: https://stackblitz.com/edit/vitejs-vite-fwbe4e?file=src/app.jsx (may need to run yarn dev in the console)