importing a javascript module in a docusaurus page - reactjs

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?

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

Related

Underline syntax with react-markdown

I'm currently running into a problem that I can't solve (I've been searching for solutions since this morning, but I can't manage to find what I need).
I created a React app using react-markdown, allowing the user to edit some post-its, whose content is stored in Markdown format in my DB. But the thing is, I discovered there was no way to underline a text (I thought that if you could do it on Discord, then it means that it's the same in Markdown).
What I'd like is a solution allowing me to simply transform this:
**Bold text**
__Underlined text__
Into... well... you know what I mean. It doesn't have to be this exact syntax, but at least something similar. The only thing I've found is to create custom components, which I don't want because it requires using an already existing syntax, or, to convert the Markdown with replace() functions and use dangerouslySetInnerHTML to display it, which I don't want either, because isn't it called "dangerouslySetInnerHTML" for a reason?
I'd really appreciate if someone could help. And by the way, sorry for any grammar mistakes, English isn't my native language...
Right now there are no identifiers for underlining text in markdown syntax.
But as you know we can achieve it by using html tags in our markdown.
But we don't have to use dangerouslySetInnerHTML in react-markdown for parsing HTML tags. react-markdown (Check Appendix A: HTML in markdown) uses a plugin rehype-raw.
You can question the thing that rehype-raw internally implements allowDangerousHtml:true, but to prevent this , we can wrap our markdown content around Dompurify.sanitize() to reduce code vulnerablity.
I also faced the same problem , so this is the approach I tried and it worked for me .
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import DOMpurify from 'dompurify';
import "./styles.css";
export default function App() {
const markdown = `
**Parsing html in react markdown**
<u>underlined text</u>
`;
return (
<div className="App">
<ReactMarkdown rehypePlugins={[rehypeRaw]}>
{DOMpurify.sanitize(markdown)}
</ReactMarkdown>
</div>
);
}
CodeSandBoxLink

Other component styles are getting applied to the component which I have not imported

Hello I am working on simple crud application in react js 18.0.0. My problem is I have my own styles for one component say eg..Home. But the styles which I have used for other components is also getting applied to Home component even though I did not imported it. Can anyone explain why?
I have attached an image for your reference.
In the above image I was in home component. But if you see the styles the container class in forgetPassword.css and login.css is also getting applied in home component. but In home component I did not imported those two css files(forgetPassword.css and login.css)
Yes this is because by default react does not support css or styles.
you can either use css modules(https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/)
Or
Use styled components.
I suggest you to try the css modules as that will be beginner friendly and easy.
You need to move your css to seperate file and name it [filename].module.css
In your case Home.module.css
Then in your Home.js component import it like import styles from './Home.module.css'
Then in your component use it like
<div className={styles.container} > ... </div>
I also recommend you not to modify the original bootstrap classes, instead create your custom class and add the overrides there.
eg:
<div className={`${styles.container} ${styles.home-container}`} > ... </div>

How to dynamically import SVG from a web service and render it inline

We have hundreds of SVG files that I am trying to render inline. I am using create-react-app which already has #svgr/webpack installed and configured. It allows me to add SVG inline like so:
import { ReactComponent as SvgImage } from '../Plans/Brownlow-Floor-Plan.svg';
...
<SvgImage style={{ width: "600px !important" }} />
Similar question provides a solution for dynamically rendering SVG inline. However, In my case, I don't have any SVG files in the source code. Instead, all SVG files are returned to me via a call to an API service. For example:
http://myservice/api/getplan(100)
http://myservice/api/getplan(103)
http://myservice/api/getplan(106)
http://myservice/api/getplan(631)
As a result, by the time webpack is run, it has no information about these SVG files.
So my question is: is it possible to render svg dynamically in react (TypeScript) if I pull SVG file from an external URL?
This is not a duplicate question:
How to dynamically import SVG and render it inline
Approach described in the question above is not going to work because it expects all SVG files to be added to the source code.
This approach also not going to work because simply using an img tag will not pull SVG inline:
<img src="plan.svg" />
Including SVG via an img tag make these kinds of things impossible:
Any help will be greatly appreciated!
There's an excellent package called react-svg that does exactly what you want.
You can use it with a simple src property that takes a url string, just like an <img> tag. But behind the scenes, it will download the svg file from the url and inject it inline. For example:
import { ReactSVG } from 'react-svg'
Component = () => <ReactSVG src="http://somewhere.com/my.svg" />,
I am not sure if this will work for you but, you can try to using the tag <use /> within an <svg /> tag. For example:
<svg
height={iconHeight}
viewBox={`0 0 ${iconWidth} ${iconHeight}`}
width={iconWidth}
>
<use xlinkHref={`${svgPath}#${icon}`} />
</svg>
Where svgPath is the URL to the SVG, and icon is an ID set on the SVG. You can try to omit to the #${icon} portion.
Not sure if this helps though.
If you choose this route, you may be incompatible with IE... For that you can use svg4everybody, but tbh IE is dead and it should stay dead.
Cheers!

Can I live preview React components in VSCode?

New to React. I have been using live server for html files in VS Code but I can't seem to find the same functionality for React components (.js files). Maybe it's obvious or I'm looking for the wrong thing.
I'd like to make changes in the component, especially MUI styling and see the incremental results in a live preview, rather than the entire application having to refresh and click back to the form I'm working on. Any thoughts or suggestions? Thanks.
You don't have to change your code when using storybook. You just have to write new files, that import your component. Then you can pass it fake props to see how it behave depending in many scenarios. If you use create-react-app, it super easy to install, if you have your own config, then your level is good enough to follow their tutorial. The files are formatted like this: MyComponent.stories.js . Then storybook will look at all files that contains "stories" in their name, and launch them on port 6006 when you write yarn/npm run storybook in your terminal. I highly recommend storybook, it is used by most of companies.
Couldn't find a satisfactory solution and not willing to invest too much. Storybook looks like I'd have to change my code and because I'm still relatively new to react, not sure I'm up for that.
I'm just letting VSCode restart server each time I save a change then going to the browser and clicking through the menus to get to the page I'm working on.
For more complex ui changes, I'll create a code sandbox mini react app and just work on that for, like css changes, etc.
UPDATE:
I've implemented Storybook and I like it. After following the doc to install it I saw that I just needed to create a file (story) for a component like MyComponent.stories.js and put in the few lines of code to import and use it, passing in whatever props I wanted to see.
I decided to put my stories files into a separate separate stories folder under src. Here's an example for a Details component:
import React from 'react';
import { action } from '#storybook/addon-actions';
import Details from '../Details';
// How to display the component in Storybook page
export default {
title: 'Details',
component: Details,
// Our exports that end in "Data" are not stories.
excludeStories: /.*Data$/
};
// Props passed into component
export const recordData = {
record: {
id: '1',
createdOn: '2020-04-20 4:07 PM',
createdBy: 'dgarv',
modifiedOn: '2020-04-20 4:07 PM',
modifiedBy: 'dgarv',
}
};
// Use the actual component
export const Default = () => <Details {...recordData} />;
I've developed an extension named AutoPreview that you can use it to preview React/Vue component in VS Code.
You can get it in extension market: https://marketplace.visualstudio.com/items?itemName=jawei.autopreviewer&ssr=false#overview
You can use Preview.js to see the rendered code - https://previewjs.com/docs/platforms/vscode

Can you use normal CSS with React?

I'm using create-react-app and have read bad things about inline styles so I wanted to use css modules however they aren't supported by create-react-app at this time. Can I literally just use plain old css in one big file? Also with this approach how do I style a react component. For example I have a component and I give it a class name: <card className="cardStyle" />. Why does this not work? I want to bed able to position it just like I would a div.
it's certainly possible, you may have plain old CSS classes in a style.css somewhere, but you'll have to make sure your app includes it,
e.g. have in your App.js
import './style.css'
The standard way is to do the following;
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles
class Button extends Component {
render() {
// You can use them as regular CSS styles
return <div className="Button" />;
}
}
See: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-a-stylesheet
Using CSS Modules might be better way:
CSS Modules have .module.css in their file name, like styles.module.css. Naming it so is important it avoids serious issue in plain CSS when having same CSS class names in different CSS files.
File : styles.module.css
.myClass1 {
background-color: red;
}
File : App.js
import styles from'./styles.module.css';
<div className={styles['myClass1']} >
some content
</div>
By default supported by Create React App - https://reactjs.org/docs/create-a-new-react-app.html
This can done using simple steps
npx create-react-app my-app
cd my-app
npm start
Links:
. https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/
. https://www.freecodecamp.org/news/how-to-style-react-apps-with-css/
If you want to use normal css but want more flexibilities like props to css, and open to install more dependencies then alternatives are:
. https://emotion.sh/docs/introduction
. https://styled-components.com/
Some are migrating styled-components to emotion, so may be emotion is better way to start with.
See https://storybook.js.org/blog/541-components-from-styled-components-to-emotion/

Resources