| 71 | * ``` |
| 72 | */ |
| 73 | export const Playground: FC<PlaygroundProps> = ({ |
| 74 | source, |
| 75 | fallback = null, |
| 76 | components, |
| 77 | scope |
| 78 | }) => { |
| 79 | const [compiledSource, setCompiledSource] = useState('') |
| 80 | const [error, setError] = useState<unknown>() |
| 81 | |
| 82 | useEffect(() => { |
| 83 | async function doCompile() { |
| 84 | // Importing in useEffect to not increase global bundle size |
| 85 | const { compileMdx } = await importCompile() |
| 86 | try { |
| 87 | const rawJs = await compileMdx(source) |
| 88 | setCompiledSource(rawJs) |
| 89 | setError(null) |
| 90 | } catch (error) { |
| 91 | setError(error) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | doCompile() |
| 96 | }, [source]) |
| 97 | |
| 98 | if (error) { |
| 99 | return ( |
| 100 | <Callout type="error"> |
| 101 | <b>Could not compile code</b> |
| 102 | <br /> |
| 103 | {error instanceof Error |
| 104 | ? `${error.name}: ${error.message}` |
| 105 | : String(error)} |
| 106 | </Callout> |
| 107 | ) |
| 108 | } |
| 109 | |
| 110 | if (compiledSource) { |
| 111 | // `<MDXRemote>` cannot be used here because `useMDXComponents` may include components that |
| 112 | // are only available on the server. |
| 113 | const MDXContent = evaluate(compiledSource, components, scope).default |
| 114 | return <MDXContent /> |
| 115 | } |
| 116 | |
| 117 | return fallback |
| 118 | } |
| 119 | |
| 120 | // Otherwise react-compiler fails |
| 121 | function importCompile() { |