Skip to content

Primer

Main navigation navigation

Live code

Doctocat can render code blocks as live previews with editable code using react-live. To make a code block render as an editable example, add a live attribute after the language:

```jsx live
<button>Hello, world!</button>
```

Here's how the above example will render on a page:

Doctocat supports live code examples for jsx and html.

Scope

Before you can use components or other variables in live code examples, you'll need to add them to the global scope of live previews. Otherwise, the live previews will display a ReferenceError, like this:

ReferenceError: Foo is not defined

You can add variables to the global scope of live previews by shadowing src/@primer/gatsby-theme-doctocat/live-code-scope.js:

// src/@primer/gatsby-theme-doctocat/live-code-scope.js
import {Box} from '@primer/react'
export default {
Box,
text: 'Hello, world!',
}

Make sure to place live-code-scope.js in the root of your gatsby-theme-doctocat folder. Shadowed files must be present in the same location as they exist in the theme repository.

Every property on the object exported by live-code-scope.js will be available as a variable in the code:

```jsx live
<Box p={3}>{text}</Box>
```

Line highlighting

If you want to emphasize a particular range of lines, use the highlight attribute on the code block. The expected format is higlight=start-end. The line highlighting will disappear when the live example is edited.

``` jsx live highlight=2-4
<div>
<p>
This paragraph element should be higlighted.
</p>
<p>
This paragraph element should not be higlighted.
</p>
</div>
```

Global styles

Live previews are completely isolated from the rest of the page because they are rendered inside iframes. This means that you can apply global styles inside live previews without affecting the rest of the page:

You can apply global styles to all live previews on your site by shadowing live-preview-wrapper.js with a component that renders a style or link tag:

// src/@primer/gatsby-theme-doctocat/components/live-preview-wrapper.js
import React from 'react'
export default function LivePreviewWrapper({children}) {
return (
<div>
<link href="https://unpkg.com/primer/build/build.css" rel="stylesheet" />
{children}
</div>
)
}

No-inline

By default, live previews treat your code as a single JSX expression to be rendered. If you want to include more complex code, use the noinline attribute on the code block, and render components with the exported render function:

```javascript live noinline
function DemoApp() {
const [count, setCount] = React.useState(0)
return (
<div>
<button onClick={() => setCount((n) => n - 1)}>-</button>
{count}
<button onClick={() => setCount((n) => n + 1)}>+</button>
</div>
)
}
render(<DemoApp />)
```