Skip to content

Commit

Permalink
docs(jsx): add explanation of automatic key insertion
Browse files Browse the repository at this point in the history
This functionality was added to Stencil in
ionic-team/stencil#5143
  • Loading branch information
alicewriteswrongs committed Jan 26, 2024
1 parent e137d3d commit 30d26b1
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions docs/components/templating-and-jsx.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,46 @@ ensure that each child has a key which does not change and which is unique
among all its siblings.
:::

### Automatic Key Insertion

During compilation Stencil will automatically add key attributes to any JSX
nodes in your component's render method which are not nested within curly
braces. This allows Stencil’s runtime to accurately reconcile children when
their order changes or when a child is conditionally rendered.

For instance, consider a render method looking something like this:

```tsx
render() {
return (
<div>
{ this.disabled && <div id="no-key">no key!</div> }
<div id="slot-wrapper">
<slot/>
</div>
</div>
);
}
```

While it might seem like adding a key attribute to the `#slot-wrapper` div
could help ensure that elements will be matched up correctly when the component
re-renders, this is actually superfluous because Stencil will automatically add
a key to that element when it compiles your component.

:::note
The Stencil compiler can only safely perform automatic key insertion in certain
scenarios where there is no danger of the keys accidentally causing elements to
be considered different when they should be treated the same (or vice versa).

In particular, the compiler will not automatically insert `key` attributes if a
component's `render` method has more than one `return` statement or if it
returns a [conditional
expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator).
Additionally, the compiler will not add key attributes to any JSX which is
found within curly braces (`{ }`).
:::

## Handling User Input

Stencil uses native [DOM events](https://developer.mozilla.org/en-US/docs/Web/Events).
Expand Down

1 comment on commit 30d26b1

@vercel
Copy link

@vercel vercel bot commented on 30d26b1 Jan 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

stencil-docs – ./

stencil-docs-ionic1.vercel.app
stencil-docs-git-main-ionic1.vercel.app
stencil-site.vercel.app

Please sign in to comment.