Skip to main content
Docusaurus

Search documentation

Type to search this documentation.

On this pageOverview

Code blocks

Code blocks within documentation are super-powered 💪.

You can add a title to the code block by adding a title key after the language (leave a space between them).

Markdown
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
  return <h1>Hello, {props.name}</h1>;
}
```
mdx-code-block
<BrowserWindow>
/src/components/HelloCodeTitle.js
function HelloCodeTitle(props) {
  return <h1>Hello, {props.name}</h1>;
}
mdx-code-block
</BrowserWindow>

Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out this reference for the specifications of MDX.

Markdown
```js
console.log('Every repo must come with a mascot.');
```

Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by Prism React Renderer.

JavaScript
console.log('Every repo must come with a mascot.');

By default, the Prism syntax highlighting theme we use is Palenight. You can change this to another theme by passing the theme field in prism as themeConfig in your docusaurus.config.js.

For example, if you prefer to use the dracula highlighting theme:

docusaurus.config.js
import {themes as prismThemes} from 'prism-react-renderer';export default {  themeConfig: {    prism: {      theme: prismThemes.dracula,    },  },};

Because a Prism theme is just a JS object, you can also write your own theme if you are not satisfied with the default. Docusaurus enhances the github and vsDark themes to provide richer highlight, and you can check our implementations for the light and dark code block themes.

By default, Docusaurus comes with a subset of commonly used languages.

To add syntax highlighting for any of the other Prism-supported languages, define it in an array of additional languages.

For example, if you want to add highlighting for the PowerShell language:

docusaurus.config.js
export default {  // ...  themeConfig: {    prism: {      additionalLanguages: ['powershell'],    },    // ...  },};

After adding additionalLanguages, restart Docusaurus.

If you want to add highlighting for languages not yet supported by Prism, you can swizzle prism-include-languages:

npm2yarn
npm run swizzle @docusaurus/theme-classic prism-include-languages

It will produce prism-include-languages.js in your src/theme folder. You can add highlighting support for custom languages by editing prism-include-languages.js:

src/theme/prism-include-languages.js
const prismIncludeLanguages = (Prism) => {  // ...  additionalLanguages.forEach((lang) => {    require(`prismjs/components/prism-${lang}`);  });  require('/path/to/your/prism-language-definition');  // ...};

You can refer to Prism's official language definitions when you are writing your own language definitions.

When adding a custom language definition, you do not need to add the language to the additionalLanguages config array, since Docusaurus only looks up the additionalLanguages strings in languages that Prism provides. Adding the language import in prism-include-languages.js is sufficient.

You can use comments with highlight-next-line, highlight-start, and highlight-end to select which lines are highlighted.

Markdown
```jsfunction HighlightSomeText(highlight) {  if (highlight) {    return 'This text is highlighted!';  }  return 'Nothing highlighted';}function HighlightMoreText(highlight) {  if (highlight) {    return 'This range is highlighted!';  }  return 'Nothing highlighted';}```
mdx-code-block
<BrowserWindow>
JavaScript
function HighlightSomeText(highlight) {  if (highlight) {    return 'This text is highlighted!';  }  return 'Nothing highlighted';}function HighlightMoreText(highlight) {  if (highlight) {    return 'This range is highlighted!';  }  return 'Nothing highlighted';}
mdx-code-block
</BrowserWindow>

Supported commenting syntax:

Style Syntax
C-style /* ... */ and // ...
JSX-style {/* ... */}
Bash-style # ...
HTML-style <!-- ... -->

We will do our best to infer which set of comment styles to use based on the language, and default to allowing all comment styles. If there's a comment style that is not currently supported, we are open to adding them! Pull requests welcome. Note that different comment styles have no semantic difference, only their content does.

You can set your own background color for highlighted code line in your src/css/custom.css which will better fit to your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly.

/src/css/custom.css
:root {
  --docusaurus-highlighted-code-line-bg: rgb(72, 77, 91);
}

/* If you have a different syntax highlighting theme for dark mode. */
[data-theme='dark'] {
  /* Color which works with dark mode syntax highlighting theme */
  --docusaurus-highlighted-code-line-bg: rgb(100, 100, 100);
}

If you also need to style the highlighted code line in some other way, you can target the theme-code-block-highlighted-line CSS class.

You can also specify highlighted line ranges within the language meta string (leave a space after the language). To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the parse-number-range library and you can find more syntax on their project details.

Markdown
```jsx {1,4-6,11}
import React from 'react';

function MyComponent(props) {
  if (props.isBar) {
    return <div>Bar</div>;
  }

  return <div>Foo</div>;
}

export default MyComponent;
```
mdx-code-block
<BrowserWindow>
JSX
import React from 'react';function MyComponent(props) {  if (props.isBar) {    return <div>Bar</div>;  }  return <div>Foo</div>;}export default MyComponent;
mdx-code-block
</BrowserWindow>

// highlight-next-line and // highlight-start etc. are called "magic comments", because they will be parsed and removed, and their purposes are to add metadata to the next line, or the section that the pair of start- and end-comments enclose.

You can declare custom magic comments through theme config. For example, you can register another magic comment that adds a code-block-error-line class name:

mdx-code-block
<Tabs>
<TabItem value="docusaurus.config.js">
JavaScript
export default {  themeConfig: {    prism: {      magicComments: [        // Remember to extend the default highlight class name as well!        {          className: 'theme-code-block-highlighted-line',          line: 'highlight-next-line',          block: {start: 'highlight-start', end: 'highlight-end'},        },        {          className: 'code-block-error-line',          line: 'This will error',        },      ],    },  },};
mdx-code-block
</TabItem>
<TabItem value="src/css/custom.css">
CSS
.code-block-error-line {
  background-color: #ff000020;
  display: block;
  margin: 0 calc(-1 * var(--ifm-pre-padding));
  padding: 0 var(--ifm-pre-padding);
  border-left: 3px solid #ff000080;
}
mdx-code-block
</TabItem>
<TabItem value="myDoc.md">
Markdown
In JavaScript, trying to access properties on `null` will error.

```js
const name = null;
// This will error
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')
```
mdx-code-block
</TabItem>
</Tabs>
mdx-code-block
<BrowserWindow>

In JavaScript, trying to access properties on null will error.

JavaScript
const name = null;
// This will error
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')
mdx-code-block
</BrowserWindow>

If you use number ranges in metastring (the {1,3-4} syntax), Docusaurus will apply the first magicComments entry's class name. This, by default, is theme-code-block-highlighted-line, but if you change the magicComments config and use a different entry as the first one, the meaning of the metastring range will change as well.

You can disable the default line highlighting comments with magicComments: []. If there's no magic comment config, but Docusaurus encounters a code block containing a metastring range, it will error because there will be no class name to apply—the highlighting class name, after all, is just a magic comment entry.

Every magic comment entry will contain three keys: className (required), line, which applies to the directly following line, or block (containing start and end), which applies to the entire block enclosed by the two comments.

Using CSS to target the class can already do a lot, but you can unlock the full potential of this feature through swizzling.

npm2yarn
npm run swizzle @docusaurus/theme-classic CodeBlock/Line

The Line component will receive the list of class names, based on which you can conditionally render different markup.

You can enable line numbering for your code block by using showLineNumbers key within the language meta string (don't forget to add space directly before the key).

Markdown
```jsx showLineNumbers
import React from 'react';

export default function MyComponent(props) {
  return <div>Foo</div>;
}
```
mdx-code-block
<BrowserWindow>
JSX
import React from 'react';

export default function MyComponent(props) {
  return <div>Foo</div>;
}
mdx-code-block
</BrowserWindow>

By default, the counter starts at line number 1. It's possible to pass a custom counter start value to split large code blocks for readability:

Markdown
```jsx showLineNumbers=3
export default function MyComponent(props) {
  return <div>Foo</div>;
}
```
mdx-code-block
<BrowserWindow>
JSX
export default function MyComponent(props) {
  return <div>Foo</div>;
}
mdx-code-block
</BrowserWindow>

(Powered by React Live)

You can create an interactive coding editor with the @docusaurus/theme-live-codeblock plugin. First, add the plugin to your package.

npm2yarn
npm install --save @docusaurus/theme-live-codeblock

You will also need to add the plugin to your docusaurus.config.js.

JavaScript
export default {  // ...  themes: ['@docusaurus/theme-live-codeblock'],  // ...};

To use the plugin, create a code block with live attached to the language meta string.

Markdown
```jsx live
function Clock(props) {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    const id = setInterval(() => {
      setDate(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <h2>It is {date.toLocaleTimeString()}.</h2>;
}
```

The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live.

mdx-code-block
<BrowserWindow>
live
function Clock(props) {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    const id = setInterval(() => {
      setDate(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <h2>It is {date.toLocaleTimeString()}.</h2>;
}
mdx-code-block
</BrowserWindow>

By default, all React imports are available. If you need more imports available, swizzle the react-live scope:

npm2yarn
npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope -- --eject
src/theme/ReactLiveScope/index.js
import React from 'react';const ButtonExample = (props) => (  <button    {...props}    style={{      backgroundColor: 'white',      color: 'black',      border: 'solid red',      borderRadius: 20,      padding: 10,      cursor: 'pointer',      ...props.style,    }}  />);// Add react-live imports you need hereconst ReactLiveScope = {  React,  ...React,  ButtonExample,};export default ReactLiveScope;

The ButtonExample component is now available to use:

mdx-code-block
<BrowserWindow>
live
function MyPlayground(props) {
  return (
    <div>
      <ButtonExample onClick={() => alert('hey!')}>Click me</ButtonExample>
    </div>
  );
}
mdx-code-block
</BrowserWindow>

The noInline option should be used to avoid errors when your code spans multiple components or variables.

Markdown
```jsx live noInline
const project = 'Docusaurus';

const Greeting = () => <p>Hello {project}!</p>;

render(<Greeting />);
```

Unlike an ordinary interactive code block, when using noInline React Live won't wrap your code in an inline function to render it.

You will need to explicitly call render() at the end of your code to display the output.

mdx-code-block
<BrowserWindow>

```jsx live noInline
const project = "Docusaurus";

const Greeting = () => (
  <p>Hello {project}!</p>
);

render(
  <Greeting />
);
```

</BrowserWindow>

Code blocks in Markdown always preserve their content as plain text, meaning you can't do something like:

TypeScript
type EditUrlFunction = (params: {
  // This doesn't turn into a link (for good reason!)
  version: <a href="/docs/versioning">Version</a>;
  versionDocsDirPath: string;
  docPath: string;
  permalink: string;
  locale: string;
}) => string | undefined;

If you want to embed HTML markup such as anchor links or bold type, you can use the <pre> tag, <code> tag, or <CodeBlock> component.

JSX
<pre>
  <b>Input: </b>1 2 3 4{'\n'}
  <b>Output: </b>"366300745"{'\n'}
</pre>

Input: 1 2 3 4

Output: "366300745"

With MDX, you can easily create interactive components within your documentation, for example, to display code in multiple programming languages and switch between them using a tabs component.

Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a general-purpose <Tabs> component in the classic theme so that you can use it for other non-code scenarios as well.

The following example is how you can have multi-language code tabs in your docs. Note that the empty lines above and below each language block are intentional. This is a current limitation of MDX: you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.

JSX
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs>
<TabItem value="js" label="JavaScript">

```js
function helloWorld() {
  console.log('Hello, world!');
}
```

</TabItem>
<TabItem value="py" label="Python">

```py
def hello_world():
  print("Hello, world!")
```

</TabItem>
<TabItem value="java" label="Java">

```java
class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}
```

</TabItem>
</Tabs>

And you will get the following:

mdx-code-block
<BrowserWindow>
<Tabs>
<TabItem value="js" label="JavaScript">
JavaScript
function helloWorld() {
  console.log('Hello, world!');
}
mdx-code-block
</TabItem>
<TabItem value="py" label="Python">
Python
def hello_world():
  print("Hello, world!")
mdx-code-block
</TabItem>
<TabItem value="java" label="Java">
Java
class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}
mdx-code-block
</TabItem>
</Tabs>
</BrowserWindow>

If you have multiple of these multi-language code tabs, and you want to sync the selection across the tab instances, refer to the Syncing tab choices section.

Displaying CLI commands in both npm and Yarn is a very common need, for example:

npm2yarn
npm install @docusaurus/remark-plugin-npm2yarn

Docusaurus provides such a utility out of the box, freeing you from using the Tabs component every time. To enable this feature, first install the @docusaurus/remark-plugin-npm2yarn package as above, and then in docusaurus.config.js, for the plugins where you need this feature (doc, blog, pages, etc.), register it in the remarkPlugins option. (See Docs configuration for more details on configuration format)

docusaurus.config.js
export default {  // ...  presets: [    [      '@docusaurus/preset-classic',      {        docs: {          remarkPlugins: [            [require('@docusaurus/remark-plugin-npm2yarn'), {sync: true}],          ],        },        pages: {          remarkPlugins: [require('@docusaurus/remark-plugin-npm2yarn')],        },        blog: {          remarkPlugins: [            [              require('@docusaurus/remark-plugin-npm2yarn'),              {converters: ['pnpm']},            ],          ],          // ...        },      },    ],  ],};

And then use it by adding the npm2yarn key to the code block:

Markdown
```bash npm2yarn
npm install @docusaurus/remark-plugin-npm2yarn
```
Option Type Default Description
sync boolean false Whether to sync the selected converter across all code blocks.
converters array 'yarn', 'pnpm' The list of converters to use. The order of the converters is important, as the first converter will be used as the default choice.

Outside of Markdown, you can use the @theme/CodeBlock component to get the same output.

JSX
import CodeBlock from '@theme/CodeBlock';

export default function MyReactPage() {
  return (
    <div>
      
      <CodeBlock
        language="jsx"
        title="/src/components/HelloCodeTitle.js"
        showLineNumbers>
        {`function HelloCodeTitle(props) {
  return <h1>Hello, {props.name}</h1>;
}`}
      </CodeBlock>
      
    </div>
  );
}
mdx-code-block
<BrowserWindow>
  <CodeBlock
    language="jsx"
    title="/src/components/HelloCodeTitle.js"
    showLineNumbers>
    {`function HelloCodeTitle(props) {
  return <h1>Hello, {props.name}</h1>;
}`}
  </CodeBlock>
</BrowserWindow>

The props accepted are language, title and showLineNumbers, in the same way as you write Markdown code blocks.

Although discouraged, you can also pass in a metastring prop like metastring='{1-2} title="/src/components/HelloCodeTitle.js" showLineNumbers', which is how Markdown code blocks are handled under the hood. However, we recommend you use comments for highlighting lines.

As previously stated, syntax highlighting is only applied when the child is a simple string.

Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu