2021年1月4日星期一

How should I manipulate HTML/markdown from a string before rendering in React?

I'm using Next.js to generate a static site from markdown content, but I want to manipulate the HTML after conversion from MD and before rendering in React -- because there is no need to do that manipulation in the browser and I want it to be statically generated. Specifically, I want to wrap images in links and <figure> tags using standard DOM methods. Currently I'm doing this with useEffect() but that does the manipulation after rendering.

As I see it, my options are:

  1. Manipulate the MD content before HTML conversion using string/regex methods.
  2. Use some library to pre-render and manipulate the DOM after HTML conversion, but what? I can't find anything that clearly shows an example of what I want.

Is there some built-in React way to handle this that I'm missing? What's the best way?

Here's a somewhat simplified version of what I'm currently doing (myData.contentHtml is already converted from markdown using remark-html):

export default function MyPage({ myData }) {    useEffect(() => {        const newEl = (el) => document.createElement(el);        document.querySelectorAll('article img[src*=".jpg"]').forEach((img) => {        let link = newEl('a');        let fig = newEl('figure');        let fc = newEl('figcaption');        let caption = img.title;        if (caption) {          fc.textContent = caption;          link.title = caption; // for lightbox          img.title = '';        }        link.href = img.src;        link.appendChild(img.cloneNode());        fig.appendChild(link);        caption && fig.appendChild(fc); // must be done after img and link        img.replaceWith(fig);      });    }, []);      return (      <article>        <h2>{myData.title}</h2>        <div dangerouslySetInnerHTML= />      </article>    );  }  
https://stackoverflow.com/questions/65554773/how-should-i-manipulate-html-markdown-from-a-string-before-rendering-in-react January 04, 2021 at 04:47AM

没有评论:

发表评论