Skip to content

Commit

Permalink
Adds context documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
kj committed Nov 17, 2023
1 parent d9cbbca commit 5dabcce
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 1 deletion.
77 changes: 77 additions & 0 deletions app/docs/md/elements/state/context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
title: Context
---

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

## Update 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](https://github.com/enhance-dev/context-demo)

Given this markup you can use the context object to pass state directly to a deeply nested child element.

<doc-code filename="app/pages/index.html">

```html
<context-parent>
<my-container>
<my-contaier>
<my-contaier>
<context-heading></context-heading>
</my-contaier>
</my-contaier>
</my-container>
</context-parent>
```

</doc-code>


Add a heading key to context in the parent element

<doc-code filename="app/pages/index.html">

```javascript
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>
`
}
```

</doc-code>

Render the heading passed via context in the deeply nested child element
<doc-code filenam="app/elements/context/heading.mjs">

```javascript
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>
`
}
```

</doc-code>


5 changes: 5 additions & 0 deletions app/docs/md/elements/state/instance-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: Instance ID
---


10 changes: 9 additions & 1 deletion app/docs/nav-data.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,15 @@ export const data = [
path: '/docs/elements/state/',
label: 'State',
hasChildren: true,
items: ['attributes', 'store'],
items: [
'attributes',
'store',
{
slug: 'instance-id',
label: 'Instance ID',
},
'context',
],
},
],
},
Expand Down

0 comments on commit 5dabcce

Please sign in to comment.