Using marked in react

前端 未结 4 1814
感动是毒
感动是毒 2020-12-25 14:50

I want to use marked in reactjs as described in the reactjs docs.

{marked(mystring)}

I use babel so I import marked

相关标签:
4条回答
  • 2020-12-25 15:42

    If you just want to import marked:

    import marked from 'marked';
    

    Then call the function in your component:

    marked('# Markdown');
    
    0 讨论(0)
  • 2020-12-25 15:46

    Here's an example on how to use marked with react:

    1. Install marked with NPM : npm i marked

    2. import it in your react app (this example is created with create-react-app), and using it example of a react component using "marked"

    3. result in the browser : preview

    0 讨论(0)
  • 2020-12-25 15:52

    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>
    )
    
    0 讨论(0)
  • 2020-12-25 15:54

    Here's one way to use marked with React:

    1. Ensure that you've installed marked
    2. Include marked in your project's package.json file:
    "dependencies": {
      "react": "^0.13.3",
      "marked": "^0.3.5"
    },
    
    1. Import marked in your .jsx (or related) file:
    import marked from 'marked';
    
    1. Use the dangerouslySetInnerHTML approach described in the tutorial7.js example in the React Tutorial (as noted by Janaka), or as shown in the example below:
    import React from 'react';
    import marked from 'marked';
    
    class MarkdownExample extends React.Component {
      getMarkdownText() {
        var rawMarkup = marked('This is _Markdown_.', {sanitize: true});
        return { __html: rawMarkup };
      }
      render() {
        return <div dangerouslySetInnerHTML={this.getMarkdownText()} />
      }
    }
    

    As discussed in the React Tutorial, using the dangerouslySetInnerHTML attribute gives you the ability to work with raw (HTML) markup. Make sure to take care when using this attribute, though!


    Note: the React.Component approach in the code example in Step 4 is based on Agnew's "Hello World" example and on notes from this React.Component vs React.createClass article by Goel and Silveira.

    0 讨论(0)
提交回复
热议问题