docs(tabs): add dynamic example

This commit is contained in:
Eric Liu 2020-11-30 11:31:48 -08:00
commit 45dfbb26cf
2 changed files with 61 additions and 12 deletions

View file

@ -33,6 +33,14 @@ components: ["Tabs", "Tab", "TabContent", "TabsSkeleton"]
</div> </div>
</Tabs> </Tabs>
### Re-rendering tabs
Use the [`#key` block](https://svelte.dev/docs#key) to dynamically update tab items or content.
The example below shows tabs and the bound `selected` index being programmatically updated.
<FileSource src="/framed/Tabs/TabsDynamic" />
### Skeleton ### Skeleton
<TabsSkeleton count={3} /> <TabsSkeleton count={3} />

View file

@ -1,5 +1,12 @@
<script> <script>
import { Button, Tabs, Tab, TabContent } from "carbon-components-svelte"; import {
ButtonSet,
Button,
Tabs,
Tab,
TabContent,
} from "carbon-components-svelte";
import { afterUpdate } from "svelte";
let tabs = [ let tabs = [
{ title: "blue", visible: true }, { title: "blue", visible: true },
@ -7,17 +14,23 @@
{ title: "red", visible: true }, { title: "red", visible: true },
]; ];
const toggleTab = (title) => {
for (const i in tabs) {
if (tabs[i].title === title) {
tabs[i].visible = !tabs[i].visible;
}
}
};
let selected = 0; let selected = 0;
afterUpdate(() => {
// if the selected tab is not visible
// reset the index to the next visible tab
if (tabs[selected].visible === false) {
selected = tabs.filter((tab) => tab.visible).length - 1;
}
});
</script> </script>
<style>
div {
margin: var(--cds-layout-02) 0;
}
</style>
{#key tabs} {#key tabs}
<Tabs bind:selected> <Tabs bind:selected>
{#each tabs as tab (tab.title)} {#each tabs as tab (tab.title)}
@ -37,6 +50,34 @@
<p>Selected index: {selected}</p> <p>Selected index: {selected}</p>
{#each tabs as { title } (title)} <div>
<Button on:click="{() => toggleTab(title)}">Toggle {title} tab</Button> <ButtonSet>
{/each} {#each tabs as { title } (title)}
<Button
kind="tertiary"
size="small"
on:click="{() => {
tabs = tabs.map((tab) => ({
...tab,
visible: tab.title === title ? !tab.visible : tab.visible,
}));
}}"
>
Toggle
{title}
tab
</Button>
{/each}
</ButtonSet>
</div>
<div>
<Button
size="small"
on:click="{() => {
selected = 1;
}}"
>
Set selected to 1
</Button>
</div>