Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(live-codeblock): add support for noInline to interactive code blocks #7514

Merged
merged 4 commits into from Jun 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -5,6 +5,9 @@
* LICENSE file in the root directory of this source tree.
*/

/// <reference types="@docusaurus/theme-classic" />
/// <reference types="@docusaurus/module-type-aliases" />

declare module '@docusaurus/theme-live-codeblock' {
export type ThemeConfig = {
liveCodeBlock: {
Expand All @@ -14,9 +17,12 @@ declare module '@docusaurus/theme-live-codeblock' {
}

declare module '@theme/Playground' {
import type {Props as BaseProps} from '@theme/CodeBlock';
import type {LiveProviderProps} from 'react-live';

export interface Props extends LiveProviderProps {
type CodeBlockProps = Omit<BaseProps, 'className' | 'language' | 'title'>;

export interface Props extends CodeBlockProps, LiveProviderProps {
children: string;
}
export default function Playground(props: LiveProviderProps): JSX.Element;
Expand Down
Expand Up @@ -93,11 +93,14 @@ export default function Playground({
} = themeConfig as ThemeConfig;
const prismTheme = usePrismTheme();

const noInline = props.metastring?.includes('noInline') ?? false;

return (
<div className={styles.playgroundContainer}>
{/* @ts-expect-error: type incompatibility with refs */}
<LiveProvider
code={children.replace(/\n$/, '')}
noInline={noInline}
transformCode={transformCode ?? ((code) => `${code};`)}
theme={prismTheme}
{...props}>
Expand Down
Expand Up @@ -556,6 +556,42 @@ function MyPlayground(props) {
</BrowserWindow>
````

### Imperative Rendering (noInline)

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

````md
```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>
````

## Using JSX markup in code blocks {#using-jsx-markup}

Code block in Markdown always preserves its content as plain text, meaning you can't do something like:
Expand Down