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
AI TipWant to skip the docs? Use the MCP Server
<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

Here's an example that adds 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.

Loading...

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()

Line numbers with word wrap

You can combine line numbers with word wrapping by setting both meta.showLineNumbers and meta.wordWrap to true. The line numbers will properly align with wrapped text.

terminal-output.txt
total 121M
  drwxr-xr-x   3 root root 4.0K Sep 11  2022  ..
  -rw-r--r--   1 ali  ali   220 Sep 11  2022  .bash_logout
  drwxr-xr-x   2 ali  ali  4.0K Sep 11  2022  Templates
  drwxr-xr-x   2 ali  ali  4.0K Sep 11  2022  Public
  -rw-r--r--   1 ali  ali     0 Sep 11  2022  .sudo_as_admin_successful
  drwx------   3 ali  ali  4.0K Sep 11  2022  .pki
  drwx------   3 ali  ali  4.0K Sep 11  2022  .gnome
  -rw-r--r--   1 ali  ali    10 Sep 13  2022  .shell.pre-oh-my-zsh
  drwxrwxr-x   3 ali  ali  4.0K Sep 26  2022  v2ray
  -rw-r--r--   1 root root  12K Sep 26  2022  .profile.swp
  drwxrwxrwx   4 ali  ali  4.0K Sep 28  2022  .sonarlint
  drwxrwxr-x   3 ali  ali  4.0K Sep 28  2022  .eclipse
  drwxrwxr-x   8 ali  ali  4.0K Oct  4  2022  zsh-syntax-highlighting
  drwxrwxr-x   2 ali  ali  4.0K Oct  5  2022  .dart
  drwxrwxr-x   4 ali  ali  4.0K Oct  5  2022  .dartServer
  drwxrwxrwx   2 ali  ali  4.0K Oct  7  2022  .quicktype-vscode
  -rw-rw-r--   1 ali  ali   38K Oct 31  2022  .zcompdump-ali-laptop-5.8.1.ali-laptop.5060
  drwxrwxr-x   3 ali  ali  4.0K Nov 16  2022  .swt
  drwx------   3 ali  ali  4.0K Nov 17  2022  .nv
  drwxrwxr-x  15 ali  ali  4.0K Nov 18  2022  .gvm
  drwxrwxr-x   2 ali  ali  4.0K Nov 27  2022  .docker-esopmoc
  drwxrwxr-x   3 ali  ali  4.0K Dec  5  2022  .ipython
  drwx------   7 ali  ali  4.0K Dec  5  2022  .local
  drwxrwxr-x   2 ali  ali  4.0K Dec  5  2022  .jupyter
  drwxr-xr-x   4 ali  ali  4.0K Dec 11  2022  .anydesk
  drwxrwxr-x   3 ali  ali  4.0K Feb 18  2023  .dotnet
  drwxrwxr-x   3 ali  ali  4.0K Feb 19  2023  .degit
  drwxrwxr-x   3 ali  ali  4.0K Feb 26  2023  .cargo
  -rw-rw-r--   1 ali  ali    21 Feb 26  2023  .zshenv
  drwxrwxr-x   6 ali  ali  4.0K Feb 26  2023  .rustup
  drwxrwxr-x   2 ali  ali  4.0K Apr  8  2023  .ipynb_checkpoints
  drwxr-xr-x   8 ali  ali  4.0K Apr 20  2023  my_folder
  drwx------   3 ali  ali  4.0K May  5  2023  .vmware
  drwxrwxr-x  15 ali  ali  4.0K May  7  2023  .openshot_qt
  drwxrwxr-x   3 ali  ali  4.0K May 10  2023  .parallel
  drwxrwxr-x   2 ali  ali  4.0K May 16  2023  .simplelocalize
  -rw-rw-r--   1 ali  ali  5.7K May 21  2023  .v8flags.9.4.146.26-node.26.86318e52f5ed4801abe1d13d509443de.json
  drwxrwxrwx 105 ali  ali  4.0K Sep  5 10:27

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