### Install react-shiki
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Install the react-shiki package using npm.
```bash
npm i react-shiki
```
--------------------------------
### Custom Language Example (mcfunction)
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Demonstrates highlighting code for a custom language, 'mcfunction', using the ShikiHighlighter component with a specific theme. This example assumes the mcfunction grammar has been loaded.
```mcfunction
tag @e[tag=mcscriptTags] add isCool
tag @e[tag=mcscriptTags] remove isCool
execute if entity @e[tag=mcscriptTags,tag=isCool] run say he is cool
tag @s add isBad
tag @s remove isBad
execute if entity @s[tag=isBad] run say he is bad
```
--------------------------------
### Core Bundle Engine Specification
Source: https://github.com/avgvstvs96/react-shiki/blob/main/package/README.md
When using the core bundle of react-shiki, an engine must be explicitly specified. This example shows how to set the JavaScript RegExp engine.
```tsx
import {
createHighlighterCore,
createOnigurumaEngine,
createJavaScriptRegexEngine
} from 'react-shiki/core';
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/nord')],
langs: [import('@shikijs/langs/typescript')],
engine: createJavaScriptRegexEngine() // or createOnigurumaEngine(import('shiki/wasm'))
});
```
--------------------------------
### Display Line Numbers with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Use the `showLineNumbers` prop to display line numbers. Customize the starting line number with `startingLineNumber`. Ensure CSS is imported for the hook.
```tsx
// Component
{code}
{code}
```
```tsx
// Hook (import 'react-shiki/css' for line numbers to work)
const highlightedCode = useShikiHighlighter(code, "javascript", "github-dark", {
showLineNumbers: true,
startingLineNumber: 0,
});
```
--------------------------------
### Displaying Line Numbers with ShikiHighlighter
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Enable line numbers for code blocks by passing the `showLineNumbers` prop to the ShikiHighlighter component. This is useful for code examples where line references are important.
```javascript
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Example usage
const result = fibonacci(10);
console.log(result); // 55
```
--------------------------------
### Integrating ShikiHighlighter with React-Markdown
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Customize how code blocks are rendered within react-markdown by using ShikiHighlighter. This example shows how to conditionally render ShikiHighlighter for fenced code blocks and standard `` for inline code.
```tsx
import ReactMarkdown from "react-markdown";
import ShikiHighlighter, { isInlineCode } from "react-shiki";
const CodeHighlight = ({ className, children, node, ...props }) => {
const code = String(children).trim();
const match = className?.match(/language-(\w+)/);
const language = match ? match[1] : undefined;
const isInline = node ? isInlineCode(node) : undefined;
return !isInline ? (
{code}
) : (
{code}
);
};
```
--------------------------------
### Core Bundle Entry Point — `react-shiki/core`
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Minimal entry point requiring a pre-built Shiki highlighter. Ideal for production apps needing precise control over shipped languages and themes.
```APIDOC
## Core Bundle Entry Point — `react-shiki/core`
### Description
Minimal entry (~12 KB) that requires the caller to supply a pre-built Shiki highlighter. Ideal for production apps that need precise control over which languages and themes ship to the client. Supports both the Oniguruma (WASM) and JavaScript regex engines.
### Core Functions
- **`createHighlighterCore`**: Function to create a core highlighter instance.
- **`createOnigurumaEngine`**: Factory for the Oniguruma (WASM) regex engine.
- **`createJavaScriptRegexEngine`**: Factory for the JavaScript regex engine.
- **`useShikiHighlighter`**: Hook for using the highlighter (requires a pre-built highlighter).
### Usage Example
#### Building a Custom Highlighter
```typescript
import {
createHighlighterCore,
createJavaScriptRegexEngine,
} from "react-shiki/core";
// Build a custom highlighter — call once (e.g. in a module-level singleton)
const highlighter = await createHighlighterCore({
themes: [import("@shikijs/themes/nord")],
langs: [
import("@shikijs/langs/typescript"),
import("@shikijs/langs/python"),
],
// Use JS engine for smaller bundle; swap for createOnigurumaEngine(import("shiki/wasm"))
engine: createJavaScriptRegexEngine(),
});
```
#### Component Usage
```tsx
import ShikiHighlighter from "react-shiki/core";
function MinimalCodeBlock({ code }: { code: string }) {
return (
{code}
);
}
```
#### Hook Usage
```tsx
import { useShikiHighlighter } from "react-shiki/core";
function MinimalHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "python", "nord", {
highlighter, // Pass the pre-built highlighter
});
return {highlighted}
;
}
```
```
--------------------------------
### Core Bundle Entry Point - react-shiki/core
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
The 'react-shiki/core' entry point offers a minimal bundle size, requiring you to supply a pre-built Shiki highlighter. This is ideal for production apps needing precise control over shipped languages and themes, supporting both Oniguruma (WASM) and JavaScript regex engines.
```tsx
import ShikiHighlighter,
{
createHighlighterCore,
createOnigurumaEngine,
createJavaScriptRegexEngine,
useShikiHighlighter,
} from "react-shiki/core";
// Build a custom highlighter — call once (e.g. in a module-level singleton)
const highlighter = await createHighlighterCore({
themes: [import("@shikijs/themes/nord")],
langs: [
import("@shikijs/langs/typescript"),
import("@shikijs/langs/python"),
],
// Use JS engine for smaller bundle; swap for createOnigurumaEngine(import("shiki/wasm"))
engine: createJavaScriptRegexEngine(),
});
function MinimalCodeBlock({ code }: { code: string }) {
return (
{code}
);
}
// Hook variant
function MinimalHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "python", "nord", {
highlighter,
});
return {highlighted}
;
}
```
--------------------------------
### Web Bundle Entry Point - react-shiki/web
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Use the 'react-shiki/web' entry point for a smaller bundle size, optimized for web languages like HTML, CSS, JS, TS, JSON, Markdown, JSX, Vue, and Svelte. The API is identical to the full bundle.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki/web";
// Component usage — identical API to the full bundle
function WebCodeBlock({ code }: { code: string }) {
return (
{code}
);
}
// Hook usage
function HookExample({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "css", "github-light");
return {highlighted}
;
}
```
--------------------------------
### Web Bundle Entry Point — `react-shiki/web`
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
A drop-in replacement for the full bundle focused on web languages. Approximately half the size of the full bundle.
```APIDOC
## Web Bundle Entry Point — `react-shiki/web`
### Description
A drop-in replacement for the full bundle focused on web languages (HTML, CSS, JS, TS, JSON, Markdown, JSX, Vue, Svelte). Approximately half the size of the full bundle (~707 KB gzipped).
### Usage
Import `ShikiHighlighter` and `useShikiHighlighter` from `react-shiki/web`.
#### Component Usage
```tsx
import ShikiHighlighter from "react-shiki/web";
function WebCodeBlock({ code }: { code: string }) {
return (
{code}
);
}
```
#### Hook Usage
```tsx
import { useShikiHighlighter } from "react-shiki/web";
function HookExample({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "css", "github-light");
return {highlighted}
;
}
```
```
--------------------------------
### Bundle Option: react-shiki/web (Web Bundle)
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Import the web bundle of react-shiki for a balance between size and functionality, including web-focused languages. It's a drop-in replacement for the main entry point.
```tsx
import ShikiHighlighter from 'react-shiki/web';
```
--------------------------------
### Bundle Option: react-shiki (Full Bundle)
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Import the full bundle of react-shiki for maximum language and theme support. This is the default import and requires no special configuration.
```tsx
import ShikiHighlighter from 'react-shiki';
```
--------------------------------
### Custom Highlighter Bundles with Core Shiki
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Optimize client-side bundle size by creating a custom highlighter using core Shiki functions and dynamic imports for languages and themes. Supports custom RegExp engines.
```tsx
import ShikiHighlighter, {
createHighlighterCore, // re-exported from shiki/core
createOnigurumaEngine, // re-exported from shiki/engine/oniguruma
createJavaScriptRegexEngine, // re-exported from shiki/engine/javascript
} from 'react-shiki/core';
// Create custom highlighter with dynamic imports to optimize client-side bundle size
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/ayu-dark')],
langs: [import('@shikijs/langs/typescript')],
engine: createOnigurumaEngine(import('shiki/wasm'))
// or createJavaScriptRegexEngine()
});
{code.trim()}
```
--------------------------------
### Using the useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Integrate syntax highlighting into your components using the useShikiHighlighter hook. This hook returns the highlighted code as a string.
```tsx
import { useShikiHighlighter } from "react-shiki";
function CodeBlock({ code, language }) {
const highlightedCode = useShikiHighlighter(code, language, "dracula");
return {highlightedCode}
;
}
```
--------------------------------
### Create Custom Highlighter with Core Bundle
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Use the core bundle for maximum bundle control in production apps. Requires custom highlighter configuration with dynamic imports for themes and languages. Choose between Oniguruma (WASM) or JavaScript RegExp engines.
```tsx
import ShikiHighlighter, {
createHighlighterCore,
createOnigurumaEngine,
createJavaScriptRegexEngine,
} from 'react-shiki/core';
// Create custom highlighter with dynamic imports to optimize client-side bundle size
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/nord')],
langs: [import('@shikijs/langs/typescript')],
engine: createOnigurumaEngine(import('shiki/wasm'))
// or createJavaScriptRegexEngine()
});
{code}
```
--------------------------------
### Optimizing Output Format for Performance
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Choose between React Nodes (default, safer) and HTML String (faster) output formats for `react-shiki` to balance safety and performance.
```tsx
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark");
// Component
{code}
```
```tsx
// Hook (returns HTML string, use dangerouslySetInnerHTML to render)
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark", {
outputFormat: 'html'
});
// Component (automatically uses dangerouslySetInnerHTML when outputFormat is 'html')
{code}
```
--------------------------------
### Use JavaScript Raw Engine with Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Employ the `ShikiHighlighter` component with the JavaScript Raw engine for pre-compiled languages. This can provide the best performance by skipping the transpilation step.
```tsx
// Component with JavaScript Raw engine (for pre-compiled languages)
// See https://shiki.style/guide/regex-engines#pre-compiled-languages
{code}
```
--------------------------------
### Custom Themes with ShikiHighlighter and useShikiHighlighter
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Import custom theme JSON files to style code snippets. This can be done using the ShikiHighlighter component or the useShikiHighlighter hook.
```tsx
import tokyoNight from "../styles/tokyo-night.json";
// Component
{code.trim()}
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", tokyoNight);
```
--------------------------------
### Specify Engine with Full/Web Bundles
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Override the default Oniguruma engine in the full and web bundles by providing an engine option to `createHighlighterCore` or `useShikiHighlighter`. This allows for optimization of bundle size and startup performance.
```tsx
import {
createHighlighterCore,
createOnigurumaEngine,
createJavaScriptRegexEngine
} from 'react-shiki/core';
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/nord')],
langs: [import('@shikijs/langs/typescript')],
engine: createJavaScriptRegexEngine() // or createOnigurumaEngine(import('shiki/wasm'))
});
```
--------------------------------
### Use JavaScript RegExp Engine with Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Utilize the `useShikiHighlighter` hook with the JavaScript RegExp engine for client-side highlighting. This engine offers a smaller bundle size and faster startup.
```tsx
import {
useShikiHighlighter,
createJavaScriptRegexEngine,
createJavaScriptRawEngine
} from 'react-shiki';
// Hook with JavaScript RegExp engine
const highlightedCode = useShikiHighlighter(code, 'typescript', 'github-dark', {
engine: createJavaScriptRegexEngine()
});
```
--------------------------------
### Using JavaScript Raw Engine with Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/package/README.md
Employ the `ShikiHighlighter` component with the JavaScript Raw engine, suitable for pre-compiled languages. This offers the best performance by skipping the transpilation step.
```tsx
// Component with JavaScript Raw engine (for pre-compiled languages)
// See https://shiki.style/guide/regex-engines#pre-compiled-languages
{code}
```
--------------------------------
### Basic ShikiHighlighter Component Usage
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Use the ShikiHighlighter component for straightforward code highlighting. Specify the language and theme directly as props.
```tsx
import ShikiHighlighter from "react-shiki";
function CodeBlock() {
return (
{code.trim()}
);
}
```
--------------------------------
### Multi-Theme Support with CSS light-dark()
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Use a Themes object for Shiki to emit CSS variables for each theme. Apply the correct variable set at runtime using the CSS `light-dark()` function. Ensure the :root CSS defines `color-scheme` for automatic switching.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
// Component — automatic switching via CSS light-dark()
function AdaptiveBlock({ code }: { code: string }) {
return (
// uses CSS color-scheme property
{code.trim()}
);
}
// Pair with :root CSS so the browser knows the current scheme
// :root { color-scheme: light; }
// :root.dark { color-scheme: dark; }
// Hook variant with explicit default theme key
function MultiThemeHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(
code,
"tsx",
{ light: "github-light", dark: "github-dark" },
{ defaultColor: "dark" }
);
return {highlighted}
;
}
```
--------------------------------
### useShikiHighlighter Hook - Full Bundle
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
The useShikiHighlighter hook provides direct control over the rendered output, returning a ReactElement or HTML string. It supports throttling for streaming use cases and configurable output formats. The full bundle is used.
```tsx
import { useShikiHighlighter } from "react-shiki";
function CodeBlock({ code, language }: { code: string; language: string }) {
const highlighted = useShikiHighlighter(
code,
language,
"github-dark",
{
delay: 150, // throttle updates (ms) — useful for streaming
outputFormat: "react", // 'react' (default) | 'html'
showLineNumbers: true,
startingLineNumber: 1,
}
);
// highlighted is null until first render, then a ReactElement
return {highlighted}
;
}
```
--------------------------------
### Preloading Custom Languages with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Use the `preloadLanguages` prop with an array of TextMate grammar objects to preload custom languages for the `ShikiHighlighter` component. This is useful for dynamic highlighting.
```tsx
import mcfunction from "../langs/mcfunction.tmLanguage.json";
import bosque from "../langs/bosque.tmLanguage.json";
// Component
{code.trim()}
```
--------------------------------
### Multi-theme Support with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Configure multiple theme modes by passing an object with 'light', 'dark', and 'dim' themes to the `theme` prop. Set `defaultColor` to 'dark' for a default dark theme.
```tsx
{code.trim()}
```
--------------------------------
### Apply Custom CSS Variables via Style Prop
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Demonstrates how to apply custom CSS variables for line number styling directly to the `ShikiHighlighter` component using the `style` prop.
```tsx
{code}
```
--------------------------------
### Custom Theme Integration
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Integrate custom TextMate themes by passing them as JavaScript objects to the `theme` prop. The object structure must conform to Shiki's ThemeRegistrationAny specification. This applies to both component and hook usage.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
import tokyoNight from "./styles/tokyo-night.json";
// Component
function CustomThemeBlock({ code }: { code: string }) {
return (
{code.trim()}
);
}
// Hook
function CustomThemeHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "tsx", tokyoNight);
return {highlighted}
;
}
```
--------------------------------
### Reactive Multi-themes using light-dark()
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Set `defaultColor` to 'light-dark()' to automatically switch themes based on the user's `color-scheme` preference. Ensure your site sets the `color-scheme` CSS property.
```tsx
// Component
{code.trim()}
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", {
light: "github-light",
dark: "github-dark",
}, {
defaultColor: "light-dark()"
});
```
```css
:root {
color-scheme: light dark;
}
/* Or dynamically for class based dark mode */
:root {
color-scheme: light;
}
:root.dark {
color-scheme: dark;
}
```
--------------------------------
### Multi-theme Support with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass a multi-theme object to the `theme` parameter of the `useShikiHighlighter` hook. The `defaultColor` option can also be specified.
```tsx
const highlightedCode = useShikiHighlighter(
code,
"tsx",
{
light: "github-light",
dark: "github-dark",
dim: "github-dark-dimmed",
},
{
defaultColor: "dark",
}
);
```
--------------------------------
### Custom Languages and Preloading
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Highlight custom or non-bundled languages by providing a TextMate grammar object to the `language` prop. Use `preloadLanguages` to load grammars eagerly, enabling dynamic language switching at runtime.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
import mcfunction from "./langs/mcfunction.tmLanguage.json";
import bosque from "./langs/bosque.tmLanguage.json";
import type { LanguageRegistration } from "react-shiki";
// Render mcfunction directly
function CustomLangBlock({ code }: { code: string }) {
return (
{code.trim()}
);
}
// Preload multiple grammars so they are available for dynamic language switching
function PreloadExample({ code, lang }: { code: string; lang: string }) {
const highlighted = useShikiHighlighter(code, lang, "github-dark", {
preloadLanguages: [mcfunction, bosque] as LanguageRegistration[],
});
return {highlighted}
;
}
```
--------------------------------
### ShikiHighlighter Component - Full Bundle
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Use the ShikiHighlighter component for rendering syntax-highlighted code blocks. It accepts props for language, theme, line numbers, and custom styling. The full bundle includes all bundled languages and themes.
```tsx
import ShikiHighlighter from "react-shiki";
function CodeBlock({ code }: { code: string }) {
return (
{code.trim()}
);
}
```
--------------------------------
### Custom Themes with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass a TextMate theme object as the third argument to the `useShikiHighlighter` hook.
```tsx
const highlightedCode = useShikiHighlighter(code, "tsx", tokyoNight);
```
--------------------------------
### Custom Languages with ShikiHighlighter and useShikiHighlighter
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Integrate custom language grammars by importing their JSON definitions. This allows highlighting code for languages not natively supported by Shiki. Both component and hook usage are shown.
```tsx
import mcfunction from "../langs/mcfunction.tmLanguage.json";
// Component
{code.trim()}
// Hook
const highlightedCode = useShikiHighlighter(code, mcfunction, "vitesse-dark");
```
--------------------------------
### Choose Output Format: React vs HTML
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Select between React-node output and faster HTML string output. The component handles `dangerouslySetInnerHTML` automatically for `outputFormat="html"`.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
// HTML output via component — dangerouslySetInnerHTML applied automatically
function FastBlock({ code }: { code: string }) {
return (
{code}
);
}
// HTML output via hook — returns string; render manually
function FastHook({ code }: { code: string }) {
const html = useShikiHighlighter(code, "tsx", "github-dark", {
outputFormat: "html",
});
if (!html) return null;
return (
// Only use with trusted code sources
);
}
```
--------------------------------
### `useShikiHighlighter` Hook — Full Bundle
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
The hook variant of the highlighter. Returns `ReactElement | string | null`. Use this when you need direct control over the rendered output.
```APIDOC
## `useShikiHighlighter` Hook — Full Bundle
### Description
The hook variant of the highlighter. Returns `ReactElement | string | null` — `null` before the first highlight completes, a `ReactElement` tree by default, or an HTML string when `outputFormat: 'html'` is set. Use this when you need direct control over the rendered output.
### Parameters
- **code** (string) - The code string to highlight.
- **language** (string) - The programming language for syntax highlighting.
- **theme** (string) - The Shiki theme to use for highlighting.
- **options** (object) - Configuration options for the highlighter.
- **delay** (number) - Throttle updates (ms) — useful for streaming (default: undefined).
- **outputFormat** (string) - Output format: 'react' (default) or 'html'.
- **showLineNumbers** (boolean) - Enable CSS-based line numbers (default: false).
- **startingLineNumber** (number) - The starting line number for line numbering (default: 1).
### Return Value
- `ReactElement | string | null` - The highlighted code, or null before the first highlight completes.
### Usage Example
```tsx
import { useShikiHighlighter } from "react-shiki";
function CodeBlock({ code, language }: { code: string; language: string }) {
const highlighted = useShikiHighlighter(
code,
language,
"github-dark",
{
delay: 150,
outputFormat: "react",
showLineNumbers: true,
startingLineNumber: 1,
}
);
return {highlighted}
;
}
```
```
--------------------------------
### Custom Languages with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass a TextMate grammar object as the second argument to the `useShikiHighlighter` hook. A theme must also be provided.
```tsx
const highlightedCode = useShikiHighlighter(code, mcfunction, "github-dark");
```
--------------------------------
### `ShikiHighlighter` Component — Full Bundle
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
The default export from `react-shiki`. Renders a syntax-highlighted code block with optional language label, line numbers, and customizable styling. Uses Shiki's full bundle.
```APIDOC
## `ShikiHighlighter` Component — Full Bundle
### Description
The default export from `react-shiki`. Renders a syntax-highlighted code block with an optional language label, line numbers, and customizable styling. Wraps `useShikiHighlighter` internally. Uses Shiki's full bundle (~1.2 MB gzipped), which includes every bundled language and theme.
### Props
- **language** (string) - The programming language for syntax highlighting.
- **theme** (string) - The Shiki theme to use for highlighting.
- **showLanguage** (boolean) - Show language label (default: true).
- **showLineNumbers** (boolean) - Enable CSS-based line numbers.
- **startingLineNumber** (number) - The starting line number for line numbering.
- **addDefaultStyles** (boolean) - Apply default styles like padding and border-radius (default: true).
- **className** (string) - Custom CSS class for the root element.
- **style** (object) - Inline styles for the root element.
- **langStyle** (object) - Inline styles for the language label.
- **as** (string) - Custom root element tag (default: "div").
### Usage Example
```tsx
import ShikiHighlighter from "react-shiki";
function CodeBlock({ code }: { code: string }) {
return (
{code.trim()}
);
}
```
```
--------------------------------
### Custom Themes with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass a TextMate theme as a JavaScript object to the `theme` prop of the `ShikiHighlighter` component. Ensure the theme object is imported correctly.
```tsx
import tokyoNight from "../styles/tokyo-night.json";
// Component
{code.trim()}
```
--------------------------------
### Custom Transformers with ShikiHighlighter and useShikiHighlighter
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Apply custom transformations to the highlighted code using the `transformers` option. This can be done with both the component and the hook, allowing for advanced code manipulation.
```tsx
import { customTransformer } from "../utils/shikiTransformers";
// Component
{code.trim()}
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", "poimandres", {
transformers: [customTransformer],
});
```
--------------------------------
### Custom Transformers with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/package/README.md
Integrate custom Shiki transformers with the useShikiHighlighter hook by including them in the 'transformers' option.
```tsx
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark", {
transformers: [customTransformer],
});
```
--------------------------------
### Use JavaScript RegExp Engine
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Replace the default Oniguruma engine with a lighter JavaScript engine for faster startup and smaller bundles. The `forgiving` flag can suppress regex errors.
```tsx
import ShikiHighlighter, {
useShikiHighlighter,
createJavaScriptRegexEngine,
createJavaScriptRawEngine,
} from "react-shiki";
// JavaScript RegExp engine — smaller, faster startup
const jsEngine = createJavaScriptRegexEngine({ forgiving: true });
function JsEngineBlock({ code }: { code: string }) {
return (
{code}
);
}
// JavaScript Raw engine — for pre-compiled grammars (best perf)
// See: https://shiki.style/guide/regex-engines#pre-compiled-languages
function RawEngineHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "typescript", "github-dark", {
engine: createJavaScriptRawEngine(),
});
return {highlighted}
;
}
```
--------------------------------
### Usage: ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Use the ShikiHighlighter component to render highlighted code blocks. Specify the language and theme for syntax highlighting.
```tsx
import ShikiHighlighter from "react-shiki";
function CodeBlock() {
return (
{code.trim()}
);
}
```
--------------------------------
### Custom Transformers with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Integrate custom Shiki transformers by passing an array of transformer functions to the `transformers` option in the configuration object for the `useShikiHighlighter` hook.
```tsx
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark", {
transformers: [customTransformer],
});
```
--------------------------------
### Implement Performance Throttling with `delay`
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Throttle highlight operations to a minimum interval using the `delay` prop. This is useful for streamed or frequently mutating code to prevent event loop saturation.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
// Component — re-highlights at most once every 150 ms
function StreamingBlock({ streamedCode }: { streamedCode: string }) {
return (
{streamedCode}
);
}
// Hook
function StreamingHook({ streamedCode }: { streamedCode: string }) {
const highlighted = useShikiHighlighter(
streamedCode,
"tsx",
"github-dark",
{ delay: 150 }
);
return {highlighted}
;
}
```
--------------------------------
### Multi-theme Support in ShikiHighlighter
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Use the ShikiHighlighter component with a theme object to specify different themes for light and dark modes. Set a default theme for initial rendering.
```tsx
{code.trim()}
```
--------------------------------
### Preloading Custom Languages with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass an array of TextMate grammar objects to the `preloadLanguages` option in the configuration object for the `useShikiHighlighter` hook.
```tsx
const highlightedCode = useShikiHighlighter(code, "typescript", "github-dark", {
preloadLanguages: [mcfunction, bosque],
});
```
--------------------------------
### Import CSS for Line Numbers Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
When using the `useShikiHighlighter` hook with line numbers, import the provided CSS file to enable styling for line numbers.
```tsx
import 'react-shiki/css';
```
--------------------------------
### Enable and Style Line Numbers
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Use the `showLineNumbers` prop to enable line numbers and customize their appearance with CSS variables. Ensure `react-shiki/css` is imported when using the hook.
```tsx
import ShikiHighlighter from "react-shiki";
// When using the hook, also import: import 'react-shiki/css';
function NumberedBlock({ code }: { code: string }) {
return (
{code}
);
}
// Available CSS variables:
// --rs-line-numbers-foreground (default: rgba(107,114,128,0.5))
// --rs-line-numbers-width (default: 2ch)
// --rs-line-numbers-padding-left (default: 0ch)
// --rs-line-numbers-padding-right(default: 2ch)
// --rs-line-numbers-font-size (default: inherit)
// --rs-line-numbers-font-weight (default: inherit)
// --rs-line-numbers-opacity (default: 1)
```
--------------------------------
### Using JavaScript RegExp Engine with react-shiki
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Opt for the JavaScript RegExp engine for a smaller client-side bundle size, avoiding the need for WASM. This can be used with both the hook and the component.
```tsx
import { useShikiHighlighter, createJavaScriptRegexEngine } from 'react-shiki';
// Use JavaScript RegExp engine (smaller bundle, no WASM)
const highlightedCode = useShikiHighlighter(code, 'typescript', 'github-dark', {
engine: createJavaScriptRegexEngine()
});
// Component usage
{code}
```
--------------------------------
### Custom Languages with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass a TextMate grammar object as the `language` prop to the `ShikiHighlighter` component. A theme must also be provided.
```tsx
import mcfunction from "../langs/mcfunction.tmLanguage.json";
// Component
{code.trim()}
```
--------------------------------
### Custom Transformers with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Integrate custom Shiki transformers by passing an array of transformer functions to the `transformers` prop of the `ShikiHighlighter` component.
```tsx
import { customTransformer } from "../utils/shikiTransformers";
// Component
{code.trim()}
```
--------------------------------
### Configure ESLint for Type-Aware Linting
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/README.md
Update the ESLint configuration to enable type-aware lint rules for production applications. Ensure `tsconfig.json` files are correctly referenced.
```javascript
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: __dirname,
},
}
```
--------------------------------
### Throttling Real-time Highlighting with Delay
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Control the update frequency of real-time code highlighting by setting a `delay` prop. This is useful for performance optimization when dealing with frequent code changes.
```tsx
// With the component
{code.trim()}
// With the hook
const highlightedCode = useShikiHighlighter(code, "tsx", "houston", {
delay: 150,
});
```
--------------------------------
### Embedded Language Highlighting with Shiki
Source: https://github.com/avgvstvs96/react-shiki/blob/main/playground/src/Demo.mdx
Demonstrates how react-shiki automatically highlights languages embedded within other languages, such as TypeScript within Markdown. No extra configuration is needed.
```markdown
# Embedded language highlighting
> react-shiki uses Shiki's `guessEmbeddedLanguages` to automatically load
> and highlight languages nested inside other languages.
## How it works
- The outer block is **Markdown**
- The inner fenced block is _TypeScript_
- Both get highlighted, no extra config needed
- Inner block is fenced with tildes (or with three backticks when the outer block uses four)
~~~typescript
const greet = (name: string): string => `Hello, ${name}!`;
console.log(greet("Alice"));
~~~
And a little **Rust** too:
~~~rust
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
fn main() {
println!("{}", greet("Alice"));
}
~~~
See the [Shiki docs](https://shiki.style) for more.
```
--------------------------------
### Language Aliases for Markdown Fences
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Map arbitrary strings to canonical Shiki language IDs using `langAlias`. This is useful when markdown fences employ non-standard identifiers, ensuring correct highlighting. Both component and hook variants support this.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
// "indents" will be treated as "python" for highlighting purposes
function AliasBlock({ code }: { code: string }) {
return (
{code.trim()}
);
}
// Hook variant
function AliasHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "indents", "github-dark", {
langAlias: { indents: "python" },
});
return {highlighted}
;
}
```
--------------------------------
### React Markdown Code Highlighting Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
A custom `CodeHighlight` component for `react-markdown` that uses `ShikiHighlighter` for syntax highlighting. It detects the language from the class name and distinguishes between inline and block code.
```tsx
import ReactMarkdown from "react-markdown";
import ShikiHighlighter, { isInlineCode } from "react-shiki";
const CodeHighlight = ({ className, children, node, ...props }) => {
const code = String(children).trim();
const match = className?.match(/language-(\w+)/);
const language = match ? match[1] : undefined;
const isInline = node ? isInlineCode(node) : undefined;
return !isInline ? (
{code}
) : (
{code}
);
};
```
--------------------------------
### Configure JavaScript RegExp Engine for Forgiving Mode
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Enable 'forgiving' mode for the JavaScript RegExp engine to achieve best-effort results with unsupported grammars. This is useful when dealing with potentially non-standard language syntax.
```typescript
createJavaScriptRegexEngine({ forgiving: true });
```
--------------------------------
### Language Aliases with ShikiHighlighter Component
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Define custom language aliases using the `langAlias` prop with an object mapping aliases to actual language names for the `ShikiHighlighter` component.
```tsx
// Component
{code.trim()}
```
--------------------------------
### Integrate CodeHighlight with ReactMarkdown
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Pass the custom `CodeHighlight` component to the `components` prop of `ReactMarkdown` to enable syntax highlighting for code blocks within markdown content.
```tsx
{markdown}
```
--------------------------------
### Custom Transformers for HAST Mutation
Source: https://context7.com/avgvstvs96/react-shiki/llms.txt
Apply custom Shiki transformers by passing an array of `ShikiTransformer` objects to the `transformers` prop. This allows mutation of the generated HAST before rendering, compatible with `@shikijs/transformers` or custom implementations.
```tsx
import ShikiHighlighter, { useShikiHighlighter } from "react-shiki";
import { transformerNotationHighlight } from "@shikijs/transformers";
// Component
function TransformerBlock({ code }: { code: string }) {
return (
{code.trim()}
);
}
// Hook
function TransformerHook({ code }: { code: string }) {
const highlighted = useShikiHighlighter(code, "typescript", "vitesse-dark", {
transformers: [transformerNotationHighlight()],
});
return {highlighted}
;
}
```
--------------------------------
### Language Aliases with useShikiHighlighter Hook
Source: https://github.com/avgvstvs96/react-shiki/blob/main/README.md
Define custom language aliases using the `langAlias` option in the configuration object for the `useShikiHighlighter` hook.
```tsx
// Hook
const highlightedCode = useShikiHighlighter(code, "indents", "github-dark", {
langAlias: { indents: "python" },
});
```
--------------------------------
### Customize Line Number CSS Variables
Source: https://github.com/avgvstvs96/react-shiki/blob/main/package/README.md
Line numbers can be customized using CSS variables. These can be applied directly via the `style` prop on the `ShikiHighlighter` component.
```css
--rs-line-numbers-foreground: rgba(107, 114, 128, 0.5);
--rs-line-numbers-width: 2ch;
--rs-line-numbers-padding-left: 0ch;
--rs-line-numbers-padding-right: 2ch;
--rs-line-numbers-font-size: inherit;
--rs-line-numbers-font-weight: inherit;
--rs-line-numbers-opacity: 1;
```
```tsx
{code}
```