4

On one of the doc/*.md pages in my documentation website I'd like to be able to have a javascript tree view thing. https://github.com/storybookjs/react-treebeard seems like it'd work well but it's not entirely clear to me how I might incorporate this javascript into one specific page.

I tried to copy the sample javascript from the Quick Start section into the specific *.md file, in a <script></script> tag, but I got a "SyntaxError: Cannot use import statement outside a module" error in the JS console.

I then took the import's out of the *.md file and put them at the top of website/siteConfig.js:

import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom';
import {Treebeard} from 'react-treebeard';

Any ideas as to where I should put these import statements?

neubert
  • 15,947
  • 24
  • 120
  • 212

1 Answers1

9

NOTE: This answer for v2 of docusaurus.

As per docusaurus documentation Introduction section, docusaurus is powered by MDX.

Write interactive components via JSX and React embedded in markdown

This allow developers to write JSX inside Markdown files and use react components same way they are used in React projects, so all you have to do is to add react-treebeard as a dependency in your project and then inside the doc/mark_down_file.md import and use treebeard same way in the example you added.

I already have a codesandbox.io project set to use treebeard library, you can see how I did it here or live view

and here is the snippet where I imported and used Treebeard:

---
id: treebeard
title: Tree beard
---

import TreeView from "../src/components/TreeView.js"

You can write JSX and use React components within your Markdown thanks to [MDX](https://mdxjs.com/).


export const Highlight = ({children, color}) => (
<span
style={{
      backgroundColor: color,
      borderRadius: '2px',
      color: '#fff',
      padding: '0.2rem',
    }}>
{children}
</span>
);

----

<TreeView />

----

<Highlight color="#25c2a0">Docusaurus green</Highlight> and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors.

I can write **Markdown** alongside my _JSX_!

Check the codesandbox for code, you can find the code for MDX file in docs/treebread.mdx and Treebread code in src/components/TreeView.js

ROOT
  • 11,363
  • 5
  • 30
  • 45
  • Looks like that requires v2 of Docusaurus, which is still in alpha. I'm currently using 1.14.4 but I'll have to play around with v2 this evening! – neubert Jan 27 '20 at 14:10
  • 1
    Nothing about V1 ... how can I do this in the version required by the question? – Fabio Russo May 06 '20 at 15:54
  • @FabioRusso, the question didn't mention anything about the version, its just stated in the comment. Is there a problem upgrading to v2? since MDX is full supported in v2, v1 is limited in that term. – ROOT May 07 '20 at 07:36
  • As v1 is about to be deprecated better to upgrade and start enjoying the benefits! – MonsCamus Mar 10 '22 at 10:43