Build faster with Premium Chakra UI Components 💎

Learn more
Skip to Content
DocsPlaygroundGuidesBlog
Sponsor

Code Block

Used to display and highlight dynamic code blocks

SourceStorybookRecipe
<div class="container">
  <h1>Hello, world!</h1>
</div>

Usage

import { CodeBlock } from "@chakra-ui/react"
<CodeBlock.AdapterProvider>
  <CodeBlock.Root>
    <CodeBlock.Header>
      <CodeBlock.Title />
      <CodeBlock.Control>
        <CodeBlock.CopyTrigger />
        <CodeBlock.CollapseTrigger />
      </CodeBlock.Control>
    </CodeBlock.Header>
    <CodeBlock.Content>
      <CodeBlock.Code>
        <CodeBlock.CodeText />
      </CodeBlock.Code>
    </CodeBlock.Content>
  </CodeBlock.Root>
</CodeBlock.AdapterProvider>

Adapters

The CodeBlock component works for Shiki and Highlight.js highlighting engines.

The docs assumes Shiki by default.

To setup the code block component, you need to:

  • Configure your preferred adapter (Shiki or Highlight.js).
  • Provide the adapter to the CodeBlock.AdapterProvider at the top level.
  • Render the CodeBlock.Root component within the CodeBlock.AdapterProvider.

Shiki

Install the shiki package.

npm install shiki

Then, create the shiki adapter that dynamically loads the shiki highlighter for the selected languages.

import type { HighlighterGeneric } from "shiki"
import { createShikiAdapter } from "@chakra-ui/react"

const shikiAdapter = createShikiAdapter<HighlighterGeneric<any, any>>({
  async load() {
    const { createHighlighter } = await import("shiki")
    return createHighlighter({
      langs: ["tsx", "json"],
      themes: ["github-dark", "github-light"],
    })
  },
})

<CodeBlock.AdapterProvider value={shikiAdapter}>
  {/* ... */}
</CodeBlock.AdapterProvider>

Highlight.js

Install the highlight.js package.

npm install highlight.js

Then, create the highlight.js adapter that dynamically loads the selected languages.

import { createHighlightJsAdapter } from "@chakra-ui/react"
import hljs from "highlight.js/lib/core"

const highlightJsAdapter = createHighlightJsAdapter<typeof hljs>({
  async load() {
    const languages = {
      tsx: () => import("highlight.js/lib/languages/typescript"),
      html: () => import("highlight.js/lib/languages/xml"),
    }
    await Promise.all(
      Object.entries(languages).map(async ([language, file]) => {
        const { default: langModule } = await file()
        hljs.registerLanguage(language, langModule)
      }),
    )
    return hljs
  },
})

Examples

Sizes

Use the size prop to change the size of the code block component.

(size=sm)
<div class="container">
  <h1>Hello, world!</h1>
</div>
(size=md)
<div class="container">
  <h1>Hello, world!</h1>
</div>
(size=lg)
<div class="container">
  <h1>Hello, world!</h1>
</div>

Title

Render the CodeBlock.Title component within the CodeBlock.Header component to add a title to the code block component.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

Copy button

Use the copyButton prop to add a copy button to the code block component.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

Line numbers

Line numbers make it easier to reference specific lines of code. Pass the meta.showLineNumbers prop to show line numbers in the code block component.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Line highlighting

Pass the meta.highlightLines prop to the CodeBlock.Root component to highlight specific lines of code. The prop accepts an array of line numbers.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Line focus

Pass the meta.highlightLines prop to the CodeBlock.Root component to highlight specific lines of code. The prop accepts an array of line numbers. The line numbers are 1-based.

const greeting = "Hello, World!"

function sayHello() {
  console.log(greeting);
}

sayHello()

Diff

Diffs are useful for highlighting source code changes. Use the meta.addedLineNumbers and meta.removedLineNumbers props to add line numbers to the code block component.

The prop accepts an array of line numbers. The line numbers are 1-based.

const greeting = "Hello, World!"; 
function sayHello() {
  console.log("Hello, World!"); 
  console.log(greeting); 
}
sayHello();

Max lines

Use the meta.maxLines prop to limit the number of lines in the code block component. By default, the code block component will expand to fit the content.

index.tsx

Language switcher

Here's an example that re-creates an API endpoint request component by composing the CodeBlock and Select components.

POST/v1/search
from github import Github

# Create a Github instance using an access token
g = Github("YOUR_ACCESS_TOKEN")

# Get a repository
repo = g.get_repo("octocat/Hello-World")

# Get repository information
print(f"Repository: {repo.name}")
print(f"Description: {repo.description}")
print(f"Stars: {repo.stargazers_count}")

# List issues
issues = repo.get_issues(state='open')
for issue in issues:
    print(f"Issue #{issue.number}: {issue.title}")

Floating copy button

Use the meta.floatingCopyButton prop to add a floating copy button to the code block component.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Tabs

Here's an example that composes the CodeBlock component with the Tabs component to create a code block with tabs.

print('Hello, World!')

Tabs sync

Here's an example that automatically syncs all code blocks that share the same storage key. Useful for package manager or framework specific code blocks in a documentation site.

npm install @chakra-ui/react
npm install @chakra-ui/react

Themes

Use the meta.colorScheme prop to add a theme to the code block component. In this example, the colorScheme is set to color mode from the useColorMode hook.

Wrap overflow

Use the meta.wordWrap prop to wrap the code block component.

index.tsx
const greeting = "Hello, World! I am a long line of text that will wrap to the next line."

function sayHello() {
  console.log(greeting)
}

sayHello()

Highlight.js

Here's an example that uses highlight.js to highlight the code block.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

Plain text

The code block falls back to a plain text by default. To create a plain text code block, remove the use of CodeBlock.AdapterProvider.

$npm install @chakra-ui/react

Props

PropDefaultType
colorPalette 'gray'
'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink'

The color palette of the component

variant 'subtle'
'solid' | 'subtle' | 'outline' | 'surface' | 'plain'

The variant of the component

size 'sm'
'xs' | 'sm' | 'md' | 'lg'

The size of the component

as
React.ElementType

The underlying element to render.

asChild
boolean

Use the provided child element as the default rendered element, combining their props and behavior.

For more details, read our Composition guide.

Previous

Code

Next

Em