Skip to content

Observed attributes break context providersΒ #65

@Rkaede

Description

@Rkaede

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions