Search code examples
htmlcssreactjsreact-markdown

How to add styling for elements in react-markdown?


I am passing various amounts of data in react markdown sich as tables, lists and h tags. I wanted to know how to style each element separately. I searched everywhere but there is no mention of how to style the elements other than just bold or emphasize, etc. I thought I could pass a class name in the ReactMarkdown component to style it but would that not just provide styling only for the component. How do I style the various elements within it?

const ReadMePreviewer = ({ readMeCode }) => {
  return (
    <ReactMarkdown
      plugins={[[gfm, { singleTilde: false }]]}
      className={style.reactMarkDown}
      // className={style.reactMarkDownRemovingExtraGlobal}
      renderers={renderers}
      source={readMeCode}
    />
  );
};


Solution

  • This is how I would make it work for me. I do it explicit with CSS and not, e.g., SCSS or CSS-in-JS so as not to bother you with extra libraries nor webpack/babel finetuning:

    Create a separate markdown-styles.module.css CSS-module file with your styles, e.g.,

    .reactMarkDown {
      // some root styles here
    }
    
    .reactMarkDown ul {
      margin-top: 1em;
      margin-bottom: 1em;
      list-style: disc outside none;
    }
    
    .reactMarkDown ul li {
      margin-left: 2em;
      display: list-item;
      text-align: -webkit-match-parent;
    }
     .reactMarkDown p { 
      font-size: 14px;
      font-weight: 400; 
      white-space: pre-wrap;
    }
    // your other styles but all under .reactMarkDown blocks
    

    Then you can import it in your component and use as you did:

    import style from './markdown-styles.module.css';
    ...
    
    const ReadMePreviewer = ({ readMeCode }) => {
      return (
        <ReactMarkdown
          plugins={[[gfm, { singleTilde: false }]]}
          className={style.reactMarkDown}
          renderers={renderers}
          children={readMeCode}
        />
      );
    };