---
title: "Code Block Button"
description: "Toggle through block-level nodes like code blocks with the code block button. More in the docs."
canonical_url: "https://tiptap.dev/docs/ui-components/components/code-block-button"
---

# Code Block Button

Toggle through block-level nodes like code blocks with the code block button. More in the docs.

A fully accessible code block button for Tiptap editors. Easily toggle selected content into a `<codeBlock>` with keyboard shortcut support and flexible customization options.

> **Interactive demo:** [code block button](https://template.tiptap.dev/preview/tiptap-ui/code-block-button)

## Installation

Add the component via the Tiptap CLI:

```bash
npx @tiptap/cli@latest add code-block-button
```

## Components

### `<CodeBlockButton />`

A prebuilt React component that toggles code block formatting.

#### Usage

```tsx
import { useEditor, EditorContent, EditorContext } from '@tiptap/react'
import { StarterKit } from '@tiptap/starter-kit'
import { CodeBlockButton } from '@/components/tiptap-ui/code-block-button'

export default function MyEditor() {
  const editor = useEditor({
    immediatelyRender: false,
    extensions: [StarterKit],
    content: `
        <pre><code>console.log('Hello, World!');</code></pre>
        `,
  })

  return (
    <EditorContext.Provider value={{ editor }}>
      <CodeBlockButton
        editor={editor}
        text="Code"
        hideWhenUnavailable={true}
        showShortcut={true}
        onToggled={() => console.log('Code block toggled!')}
      />

      <EditorContent editor={editor} role="presentation" />
    </EditorContext.Provider>
  )
}
```

#### Props

| Name                  | Type             | Default     | Description                                        |
| --------------------- | ---------------- | ----------- | -------------------------------------------------- |
| `editor`              | `Editor \| null` | `undefined` | The Tiptap editor instance                         |
| `text`                | `string`         | `undefined` | Optional text label for the button                 |
| `hideWhenUnavailable` | `boolean`        | `false`     | Hides the button when code block is not applicable |
| `onToggled`           | `() => void`     | `undefined` | Callback fired after a successful toggle           |
| `showShortcut`        | `boolean`        | `false`     | Shows a keyboard shortcut badge (if available)     |

## Hooks

### `useCodeBlock()`

A custom hook to build your own code block toggle button with full control over rendering and behavior.

#### Usage

```tsx
import { useCodeBlock } from '@/components/tiptap-ui/code-block-button'
import { parseShortcutKeys } from '@/lib/tiptap-utils'
import { Badge } from '@/components/tiptap-ui-primitive/badge'

function MyCodeBlockButton() {
  const { isVisible, isActive, canToggle, handleToggle, label, shortcutKeys, Icon } = useCodeBlock({
    editor: myEditor,
    hideWhenUnavailable: true,
    onToggled: () => console.log('Code block toggled!'),
  })

  if (!isVisible) return null

  return (
    <button onClick={handleToggle} disabled={!canToggle} aria-label={label} aria-pressed={isActive}>
      <Icon />
      {label}
      {shortcutKeys && <Badge>{parseShortcutKeys({ shortcutKeys })}</Badge>}
    </button>
  )
}
```

#### Props

| Name                  | Type             | Default     | Description                                      |
| --------------------- | ---------------- | ----------- | ------------------------------------------------ |
| `editor`              | `Editor \| null` | `undefined` | The Tiptap editor instance                       |
| `hideWhenUnavailable` | `boolean`        | `false`     | Hides the button if code block cannot be applied |
| `onToggled`           | `() => void`     | `undefined` | Callback fired after toggling code block         |

#### Return Values

| Name           | Type            | Description                                   |
| -------------- | --------------- | --------------------------------------------- |
| `isVisible`    | `boolean`       | Whether the button should be rendered         |
| `isActive`     | `boolean`       | If the code block is currently active         |
| `canToggle`    | `boolean`       | If the code block toggle is currently allowed |
| `handleToggle` | `() => boolean` | Function to toggle code block formatting      |
| `label`        | `string`        | Accessible label text for the button          |
| `shortcutKeys` | `string`        | Keyboard shortcut (Cmd/Ctrl + Alt + C)        |
| `Icon`         | `React.FC`      | Icon component for the code block button      |

## Utilities

### `canToggle(editor, turnInto?)`

Checks if code block can be toggled in the current editor state.

**Parameters:**

- `editor`: `Editor | null` - The Tiptap editor instance
- `turnInto`: `boolean` - Whether to check for convertible node types (default: `true`)

**Returns:** `boolean` - Whether the code block can be toggled

```tsx
import { canToggle } from '@/components/tiptap-ui/code-block-button'

const canToggleBlock = canToggle(editor) // Check if can toggle
const canTurnInto = canToggle(editor, true) // Explicit: check if selection can be turned into a code block
const canToggleDirect = canToggle(editor, false) // Check if can toggle directly
```

### `toggleCodeBlock(editor)`

Programmatically toggles code block formatting for the current selection.

**Parameters:**

- `editor`: `Editor | null` - The Tiptap editor instance

**Returns:** `boolean` - Whether the toggle was successful

```tsx
import { toggleCodeBlock } from '@/components/tiptap-ui/code-block-button'

const success = toggleCodeBlock(editor)
if (success) {
  console.log('Code block toggled successfully!')
}
```

### `shouldShowButton(props)`

Determines if the code block button should be shown based on editor state and configuration.

**Parameters:**

- `props`: `object`
  - `editor`: `Editor | null` - The Tiptap editor instance
  - `hideWhenUnavailable`: `boolean` - Whether to hide when unavailable

**Returns:** `boolean` - Whether the button should be shown

```tsx
import { shouldShowButton } from '@/components/tiptap-ui/code-block-button'

const shouldShow = shouldShowButton({
  editor,
  hideWhenUnavailable: true,
})
```

## Keyboard Shortcuts

The code block button supports the following keyboard shortcut:

- **Cmd/Ctrl + Alt + C**: Toggle code block formatting

The shortcut is automatically registered when using either the `<CodeBlockButton />` component or the `useCodeBlock()` hook.

## Requirements

### Dependencies

- `@tiptap/react` - Core Tiptap React integration
- `@tiptap/starter-kit` - Basic Tiptap extensions including code block support
- `react-hotkeys-hook` - Keyboard shortcut management

### Referenced Components

- `use-tiptap-editor` (hook)
- `button` (primitive)
- `badge` (primitive)
- `tiptap-utils` (lib)
- `code-block-icon` (icon)
