Using marked in react - reactjs

I want to use marked in reactjs as described in the reactjs docs.
<div>{marked(mystring)}</div>
I use babel so I import marked like this:
import { marked } from 'marked';
Unfortunately the import statement does not work. marked is not defined.
How do I have to import marked here, so that I can use it?

Here's one way to use marked with React:
Ensure that you've installed marked
Include marked in your project's package.json file:
// package.json
{
dependencies: {
react: "^17.0.0",
marked: "^4.0.0",
},
}
Import marked in your .jsx (or related) file:
import { marked } from "marked";
Use the dangerouslySetInnerHTML approach as shown in the example below:
import React from "react";
import { marked } from "marked";
class MarkdownExample extends React.Component {
getMarkdownText() {
var rawMarkup = marked.parse("This is _Markdown_.");
return { __html: rawMarkup };
}
render() {
return <div dangerouslySetInnerHTML={this.getMarkdownText()} />;
}
}
The dangerouslySetInnerHTML attribute gives you the ability to work with raw (HTML) markup. Make sure to take care when using this attribute, though!
Alternative (Safe)
If you don't want to use dangerouslySetInnerHTML and safely render HTML. Try marked-react, which internally uses marked to render the html elements as react components
npm i marked-react
import Markdown from "marked-react";
const MarkdownComponent = () => {
return <Markdown>{rawmarkdown}</Markdown>;
};
Another alternative is react-markdown

Here is another way of using marked with React Hooks:
Create your MarkedConverter component
import { useState } from 'react'
import marked from 'marked'
export const MarkedConverter = () => {
const [markedVal, setMarkedVal] = useState(
'# Welcome to my React Markdown Previewer!'
)
return <div dangerouslySetInnerHTML={createMarkUp(markedVal)}></div>
}
Create Markup function and pass the value from MarkedConverter Component
export const createMarkUp = (val) => {
return { __html: marked(val) }
}
Finally you can import MarkedConverter Component to any of your Component

With the marked-wrapper react-marked-markdown:
import { MarkdownPreview } from 'react-marked-markdown'
export default ({ post }) => (
<div>
<h1>{ post.title }</h1>
<MarkdownPreview value={ post.content }/>
</div>
)

If you just want to import marked:
import marked from 'marked';
Then call the function in your component:
marked('# Markdown');

Here's an example on how to use marked with react:
Install marked with NPM : npm i marked
import it in your react app (this example is created with create-react-app), and using it
example of a react component using "marked"
result in the browser :
preview

Related

If possible, how to use MUI with Qwik framework?

I try Qwik framework which looks a lot like Reactjs and uses jsx. And suddenly, I wonder if Reactjs libraries such as MUI can work with Qwik framework.
I tried this code:
import { component$ } from "#builder.io/qwik";
import Add from "#mui/icons-material/Add";
import IconButton from "#mui/material/IconButton";
const AddToCartButton = component$(() => {
return (
<IconButton>
<Add />
</IconButton>
);
});
export default AddToCartButton;
But I got this this error:
QWIK ERROR Code(25): Invalid JSXNode type. It must be either a function or a string. Found: {
'$$typeof': Symbol(react.memo),
type: {
'$$typeof': Symbol(react.forward_ref),
render: [Function: Component] { displayName: 'AddIcon', muiName: 'SvgIcon' }
},
compare: null
} Error: Code(25): Invalid JSXNode type. It must be either a function or a string. Found:
at logError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4515:58)
at logErrorAndStop (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4521:21)
at qError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4585:16)
at Proxy.jsx (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:605:23)
at AddToCartButton_component_4S0nJgnxzBU (/src/addtocartbutton_component_4s0njgnxzbu.js:11:55)
at useInvoke (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:149:30)
at E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4676:32
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async renderSSR (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:5280:9)
at async Proxy.renderToStream (E:\qwik\flower\node_modules\#builder.io\qwik\server.cjs:582:3)
at async file:///E:/qwik/flower/node_modules/#builder.io/qwik/optimizer.mjs:1776:30
QWIK ERROR Code(25): Invalid JSXNode type. It must be either a function or a string. Found: Error: Code(25): Invalid JSXNode type. It must be either a function or a string. Found:
at logError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4515:58)
at logErrorAndStop (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4521:21)
at qError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4585:16)
at Proxy.jsx (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:605:23)
at AddToCartButton_component_4S0nJgnxzBU (/src/addtocartbutton_component_4s0njgnxzbu.js:11:55)
at useInvoke (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:149:30)
at E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4676:32
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async renderSSR (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:5280:9)
at async Proxy.renderToStream (E:\qwik\flower\node_modules\#builder.io\qwik\server.cjs:582:3)
at async file:///E:/qwik/flower/node_modules/#builder.io/qwik/optimizer.mjs:1776:30
not rendered
JSX in this case is the templating language of Qwik but the underlyings are different. It is made similar so you have an easier transition from react as stated in their docs.
Qwik is familiar for React developers and can be used to build any type of web site or application.
Qwik offers some adapter for react components you need to install and wrap your components in.
npm i -D #builder.io/qwik-react
And then the usage should look like the example in their repo.
/** #jsxImportSource react */
import { qwikify$ } from '#builder.io/qwik-react';
import { Button } from '#mui/material';
export const App = qwikify$(() => {
return (
<>
<Button variant="contained">Hola</Button>
</>
);
});
This thread is a bit older but maybe someone stumbles across it like me.
I had the same issue using a UI-component library and resolved it with the following steps.
adding qwikReact into the vite.config file:
import { defineConfig } from "vite";
import { qwikVite } from "#builder.io/qwik/optimizer";
import { qwikCity } from "#builder.io/qwik-city/vite";
import { qwikReact } from "#builder.io/qwik-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig(() => {
return {
plugins: [qwikCity(), qwikVite(), qwikReact(), tsconfigPaths()],
preview: {
headers: {
"Cache-Control": "public, max-age=600",
},
},
};
});
qwikify() must be used in a seperate file only with /** #jsxImportSource react */ as Jonathan pointed out.
Be aware that react components will not be treated the same way in Qwik. As stated in the docs it should be a migration/testing tool for existing projects where react components should be introduced in "Wide islands".
For those of you who are using Qwik Speak for I18N, the proposed solution will not work as is because Qwik-Speak won't be able to handle the JSX. The solution is to individually wrap the MUI component and then use it normally as so:
import { component$ } from "#builder.io/qwik";
import { Link } from "#builder.io/qwik-city";
import { $translate as t, Speak } from "qwik-speak";
import Button from "#mui/material/Button";
import { qwikify$ } from "#builder.io/qwik-react";
export const MUIButton = qwikify$(Button);
export default component$(() => {
return (
<Speak assets={["welcome"]}>
<div>
<h1>{t("welcome.title##Welcome")}</h1>
<MUIButton variant="contained">Do Something</MUIButton>
</div>
</Speak>
);
})

react says Error: Invalid hook call when I try to use material makestyles

I'm new to react and I'm trying to using makestyles and this is how :
in Header.jsx :
import React from "react";
import UseStyles from "./Header_style";
function Header() {
const classes =UseStyles();
return (
<div className={"Main-Header"}>
<div className={"Header-Logo"}>
<div className={classes.test}>test</div>
</div>
</div>
);
};
export default Header;
and style.js :
import {makeStyles} from '#material-ui/styles';
const UseStyles = makeStyles(theme=>({
test: {
backgroundColor: '#BDC3C7',
color :'red !important',
widtH : '18%'
},
}));
export default UseStyles;
but I'm getting folwing error:
×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
*edit:
This is how I'm using Header :
import React, { Component } from 'react'
import Header from './component/heder/Header.jsx';
class App extends Component {
constructor() {
super();
this.state = {
monsters: [],
searchField: ''
};
}
render() {
return (
<Header/>
);
}
}
export default App;
and another thing, I'm getting following error too :
When you place your Header component in the return or render of a parent component make sure you use <Header /> and not {Header}
additionally if that's not the problem you can check this link which is the official react thread on that error.
Also posting how you render the component that is throwing the error would be very helpful.
Edit* Additionally you don't need to call makeStyles with a function. Since you are not using the theme, you can just call makeStyles with an object like this
const useStyles = makeStyles({
test: {
background: 'white',
width: '100%'
}
});
EDIT and additional answers:
Here's a snippet from MUI's official page on styles:
The way you import makeStyles:
import { makeStyles } from '#material-ui/styles
If you import this way you have to have applied the #material-ui/styles module.
If instead in your package.json you use '#material-ui/core and haven't installed #material-ui/styles you could be getting that error because you don't have the module #material-ui/styles.
If you just have #material-ui/core you can still import makeStyles without installing the standalone #material-ui/styles it is all included in #material-ui/core.
Simply import it like this instead:
import { makeStyles } from '#material-ui/core/styles'
everybody, I've found the solution!
have to use withStyles.

install quilljs-markdown on react

I need such an editor on react https://cloverhearts.github.io/quilljs-markdown/ , as you can see in it you can put markdown characters directly into the text.
when I do this
import React, { Component } from 'react'
import './App.css'
import ReactQuill from 'react-quill'
import Quill from 'quill'
import QuillMarkdown from 'quilljs-markdown'
const App = () => {
const editor = new Quill('#editor', {
theme: 'snow'
})
new QuillMarkdown(editor)
return (
<div className='app'>
{/*<MyComponent/>*/}
<div id="editor"></div>
</div>
)
}
export default App
I get error TypeError: Cannot read property 'on' of undefined
as I understand I need jQuery for work, but I use react, I found https://www.npmjs.com/package/react-quill this quilljs for react, but I don't know how to combine it with markdown https://www.npmjs.com/package/quilljs-markdown
can anyone help?
I found the solution for this after hours of trying this out.
What you have to do is this:
Create a module for ReactQuill
Register the module.
Pass modules to react quill
Shown Below.
Step 01
const modules = {
markdownOptions: {}
};
Step 02
Quill.register('modules/markdownOptions', QuillMarkdown);
Step 03
<ReactQuill
modules={modules}
/>
It seems like you are trying to initialize the Quill instance and the markdown module before the editor is ready.
Use useEffect hook to initialize it after the div has been rendered:
import {useEffect} from 'react';
...
useEffect(() => {
const editor = new Quill('#editor', {
theme: 'snow'
});
new QuillMarkdown(editor);
});

complex layout using react storybook

I am new to react storybook and have created relatively simple stories so far as mentioned below:
import React from 'react';
import { action } from '#storybook/addon-actions';
export default {
title: "Test"
}
export const test = () => <textarea onClick={action('textarea clicked')}>Hong test from me</textarea>;
export const input = () => <input type="text"></input>;
With this knowledge, I want to go ahead and create complex stories i.e. as shown in the image below:
Is there any tutorial which will help me achieve this.
Thanks
I am not sure if I understood your question correctly, but I will try to give you an answer.
What we usually do with storybook stories is to create the story and then import a complex component inside it.
import React from 'react';
import { storiesOf } from '#storybook/react';
import { CustomComponent } from '../src';
storiesOf('CustomComponent', module)
.add('Custom Component story 1', () => (
<CustomComponent />
));

Use NPM package in React Component

I try to use Pannellum NPM package in my React component.
Pannellum's API can be used like this:
pannellum.viewer('panorama', {
"type": "equirectangular",
"panorama": "https://pannellum.org/images/alma.jpg"
});
I thought the following code:
import React, { Component } from 'react';
import './App.css';
import pannellum from 'pannellum';
class App extends Component {
componentDidMount() {
pannellum.viewer('panorama', {
"type": "equirectangular",
"panorama": "https://pannellum.org/images/alma.jpg"
});
}
render() {
return (
<div id="panorama"></div>
);
}
}
export default App;
would work. However it does not. I get TypeError: __WEBPACK_IMPORTED_MODULE_2_pannellum___default.a.viewer is not a function.
Tried also a different import statements:
import { pannellum } from 'pannellum';, const pannellum = require('pannellum'); but these also don't work.
What's interesting, Pannellum's API javascript code is bundled and once I comment out componentDidMount() and try to use the API via Chrome Dev Tools console once the page is loaded, it works. However there are no CSS styles applied.
I clearly do something wrong.
I have seen 360-react-pannellum package source code but I need access to the whole API, not just rendering so it does not suit my needs.
Thank you for your help.
Looking at the source code of pannellum, it does not export any module but puts everything on the window object.
Try importing the code and using it directly from the window.
import React, { Component } from 'react';
import './App.css';
import 'pannellum';
class App extends Component {
componentDidMount() {
window.pannellum.viewer('panorama', {
"type": "equirectangular",
"panorama": "https://pannellum.org/images/alma.jpg"
});
}
render() {
return (
<div id="panorama"></div>
);
}
}
export default App;
Try
componentDidMount() {
window.pannellum.viewer('panorama', {
"type": "equirectangular",
"panorama": "https://pannellum.org/images/alma.jpg"
});
}

Resources