How can Tailwind/typography work well with markdown-it in a React project?

3.8k Views Asked by At

I'm attempted to develop a new feature for my blog, that is a Markdown editor for writing articles.

I chosed @tailwindcss/typography and markdown-it to do that, so this is my whole dependencies:

package.json

{
 "dependencies": {
    "firebase": "^9.0.0-beta.7",
    "markdown-it": "^12.2.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "@tailwindcss/typography": "^0.4.1",
    "autoprefixer": "^10.3.2",
    "babel-loader": "^8.2.2",
    "css-loader": "^6.2.0",
    "dotenv-webpack": "^7.0.3",
    "html-webpack-plugin": "^5.3.2",
    "postcss": "^8.3.6",
    "postcss-cli": "^8.3.1",
    "postcss-loader": "^6.1.1",
    "style-loader": "^3.2.1",
    "tailwindcss": "^2.2.7",
    "webpack": "^5.51.1",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^4.0.0"
  }
}

Below code is the component for this feature, including a editing area and a preview area. However, it didn't work.

When I run this code, it is rendered out like this, without typographing the <h1> tag.

However, if I repalce md.render(markdown) with <h1>hello</h1>(the markdown-it's rendering result), it seems "work", looking like this.

Editor.jsx
import React, { useState } from "react";
const md = require("markdown-it")('commonmark');


const Editor = () => {
  const [markdown, setMarkdown] = useState("# hello");
  const onTextChange = (e) => {
    setMarkdown(e.target.value);
  }

  return (
    <div>
      <form>
        <textarea onChange={(e) => onTextChange(e)}>
          {markdown}
        </textarea>
      </form>

      <div id="preview" className="prose">
        {md.render(markdown)} {/* <h1>hello</h1> */}
      </div>

    </div>
  )
}

export default Editor;

Why these things happened? and how can I make it run with expections?

1

There are 1 best solutions below

1
On BEST ANSWER

use react-markdown instead of markdown-it

here is an example:

import ReactMarkdown from "react-markdown";

<div className="prose">
    <ReactMarkdown>{markdown}</ReactMarkdown>
</div>

it will render the provided content as DOM in the page, and Tailwind/typography perfectly styles those elements.