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 });
When a custom element has an observed attribute, a context provider will not take a value.
Full working example: https://stackblitz.com/edit/vitejs-vite-fwbe4e?file=src/app.jsx (may need to run
yarn dev
in the console)