Convert JSX to String


Install ReactDOM

npm i react-dom/server

You import them like this

import { renderToString, renderToStaticMarkup } from 'react-dom/server';

I’ll use a MyPage class, but you can insert any HTML tags directly.

Without Tags (text only)

Method 1

renderToString(<MyPage />).replace(/(<([^>]+)>)/gi, "");

Method 2

renderToStaticMarkup(<MyPage />).replace(/<[^>]*>/g, "")

Method 3

const tmp = document.createElement("div");
tmp.innerHTML = renderToString(<MyPage />);
const without_tags = tmp.textContent || tmp.innerText || '';

With Tags

With HTML tags

renderToString(<MyPage />)

With markup tags

renderToStaticMarkup(<MyPage />)

Leave a Reply

Your email address will not be published. Required fields are marked *