Astro Tabbed Code Block

March 25, 2024 Updated: April 25, 2024

Astro Tabbed Code Block

Table of Contents

Astro Subcomponents

The following components are the building blocks for the tabbed code block. The block.astro component is the main component that wraps the code block. The nav.astro component is the navigation bar that allows users to switch between tabs. The frame.astro component is the frame that wraps the code block and allows for scrolling. The lang.astro component is the language label that appears at the top right of the code block.

Diagram

The following diagram shows how the components are structured and how they interact with each other.

Click to open full screen

The Component

The code.astro and pre.astro components are also subcomponents of the tabbed.astro component. However, they can also be used used as the default components for rendering markdown code blocks wrapped with single or triple backticks. For more information about assigning custom components to HTML elements in .mdx files, see the Astro documentation.

The tabbed.astro compoennt is the main component that creates the tabbed code block. The component includes the CodeBlock, CodeNav, CodeLang, and CodeFrame components.

Example

The tabbed.astro component is used to wrap markdown codeblocks triple backticks like the following example. Without the tabbed.astro component, the code block would still be rendered thanks to pre.astro and code.astro components, but without tabs.

For more examples, you can look at the source code for this page.

mdx
import TabbedCode from "$/components/markdown/code/tabbed.astro";

<TabbedCode>
<Fragment slot="tab-1">pre.astro</Fragment>
<Fragment slot="panel-1">
``‍`astro
---
import { cn } from "$/util";
import CodeBlock from "./block/block.astro";
import CodeFrame from "./block/frame.astro";
import CodeLang from "./block/lang.astro";
import CodeNav from "./block/nav.astro";
---

<CodeBlock class="group-[.tabbed]:m-0 group-[.tabbed]:border-0">
	<CodeNav class="group-[.tabbed]:hidden" />
	<CodeLang class="group-[.tabbed]:top-0">
		{Astro.props.lang}
	</CodeLang>
	<CodeFrame class="group-[.tabbed]:max-h-none">
		<pre class={cn(Astro.props.class, "group my-1")}><slot /></pre>
	</CodeFrame>
</CodeBlock>
``‍`
</Fragment>
<Fragment slot="tab-2">code.astro</Fragment>
<Fragment slot="panel-2">
``‍`astro
---
import { cn } from "$/util";
---

<code
	class={cn(
		Astro.props.class,
		"group-[.astro-code]:bg-transparent group-[.astro-code]:text-xs rounded-sm bg-white/20 text-base-content",
		"[#table-of-contents+ul_&]:bg-transparent [#table-of-contents+ul_&]:font-montserrat",
		"[:is(h1,h2,h3,h4)>&]:bg-transparent [:is(h1,h2,h3,h4)>&]:font-robo-flex"
	)}><slot /></code>

``‍`
</Fragment>
</TabbedCode>