Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
    />
  );
};
like image 574
bros Avatar asked Mar 04 '26 12:03

bros


1 Answers

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}
    />
  );
};
like image 195
Madrus Avatar answered Mar 06 '26 02:03

Madrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!