Context

The context object enables passing state to child elements without needing to resort to passing attributes down through multiple elements.

Set parent context

The context object is passed as a key on the state object. Add data to the context object and it will be available to child elements.

Follow along by checking out the context demo from GitHub →

Given this markup you can use the context object to pass state directly to a deeply nested child element. Consider the page structure in the example below:

<context-parent>
  <my-container>
    <my-container>
      <my-container>
        <context-heading></context-heading>
      </my-container>
    </my-container>
  </my-container>
</context-parent>

Add a heading key to the context object in the parent element:

export default function ContextParent({ html, state }) {
  const { context } = state
  context.heading = 'Heading set via context'
  return html`
<style>
 :host {
   display: block;
   height: 100dvh;
   padding-top: 3rem;
   text-align: center;
   font-family: sans-serif;
 }
</style>
<slot></slot>
  `
}

Render the heading passed via context in the deeply nested child element:

export default function ContextHeading({ html, state }) {
  const { context } = state
  const { heading='Default heading' } = context
  return html`
<style>
  :host > h1 {
    font-size: 1.5rem;
  }
</style>
<h1>${heading}</h1>
  `
}

Community Resources

GitHub
Visit Enhance on GitHub.
Discord
Join our Discord server to chat about development and get help from the community.
Mastodon
Follow Enhance in the Fediverse. We're huge fans of the IndieWeb!