Sync and persistence
Make related groups switch together, and remember the reader's choice in local storage or the URL.
A reader who picks pnpm in one install block usually wants pnpm in every block on the page, and on the next page too. Two attributes on rich groups handle this:
syncjoins groups under a shared key.persistsaves the selection for that key.
Sync
Groups with the same sync key switch together. The client matches tabs by value, not by position or label.
:::: code-group label="Package manager" sync="pm-demo"
::: code-tab label="npm" value="npm"
```sh
npm install rehype-code-group
```
:::
::: code-tab label="pnpm" value="pnpm"
```sh
pnpm add rehype-code-group
```
:::
::::Try it: choose a tab in either group below.
npm install rehype-code-grouppnpm add rehype-code-groupyarn add rehype-code-groupnpm run buildpnpm run buildyarn run buildHow it behaves:
- A group that has no tab with the chosen value keeps its current tab.
- Groups added to the page later, for example after client-side navigation, start on the value last chosen for their key.
- Only the group you clicked fires the
rehype-code-group:changeevent. The groups that follow it don't. - Compact groups have no attributes, so they can't sync. Convert a group to the rich syntax to give it a
synckey.
Persist
persist decides where the choice for a sync key is stored. It does nothing without sync, because the key names the stored value.
| Value | Stored in | Good for |
|---|---|---|
local | localStorage, under rehype-code-group:<sync key> | Remembering a reader's preference across pages and visits. |
url | The query string, as ?rcg-<sync key>=<value> | Links that open with a particular tab selected. |
With persist="url", the client updates the address with history.replaceState. That changes the current history entry without adding a new one, so the back button isn't affected.
If storage is unavailable, for example in some private browsing modes or sandboxed frames, the client keeps working and doesn't save the choice.
Which tab is selected on load
When the client sets up a group, it picks the first of these that matches one of the group's tab values:
- The persisted value: the URL parameter for
persist="url", or local storage forpersist="local". - The value already chosen for the same
synckey earlier in this page session. - The
defaultattribute, which is already in the generated HTML. - The first tab.
When a persisted value is found, other enhanced groups with the same key switch to it too.
This page's demos use sync="pm-demo" without persist, so reloading the page resets them.