Tabs

Show multiple code blocks in tabs.

content.mdx
<CodeWithTabs>
```js !!tabs main.js
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}
```
```css !!tabs styles.css
body {
margin: 0;
padding: 0;
}
```
</CodeWithTabs>
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}

Implementation

We use the Tabs components from shadcn/ui:

npx shadcn@latest add tabs

And then create a component to handle multiple codeblocks as tabs:

code.tsx
import { Block, CodeBlock, parseProps } from "codehike/blocks"
import { Pre, highlight } from "codehike/code"
import { z } from "zod"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
const Schema = Block.extend({ tabs: z.array(CodeBlock) })
async function CodeWithTabs(props: unknown) {
const { tabs } = parseProps(props, Schema)
return <CodeTabs tabs={tabs} />
}
export async function CodeTabs(props: { tabs: RawCode[] }) {
const { tabs } = props
const highlighted = await Promise.all(
tabs.map((tab) => highlight(tab, "github-dark")),
)
return (
<Tabs defaultValue={tabs[0]?.meta} className="">
<TabsList className="">
{tabs.map((tab) => (
<TabsTrigger key={tab.meta} value={tab.meta}>
{tab.meta}
</TabsTrigger>
))}
</TabsList>
{tabs.map((tab, i) => (
<TabsContent key={tab.meta} value={tab.meta} className="">
<Pre code={highlighted[i]} className="" />
</TabsContent>
))}
</Tabs>
)
}