Skip to content

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/components'
export default {
Box,
text: 'Hello, world!',
}

Note: 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>
```

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 />)
```