#REACT Convert a JSX.Element to an HTMLElement

Viewed 10903

I want to use this library for my react js project https://www.npmjs.com/package/html-to-image.

In my case I want to use a var that contain a simple div and export It as an Image, but there's a problem: my var (node) is a JSX.Element and the "toPng" method of the library accept as a parameter an HTMLElement.

enter image description here

enter image description here

I know that the doc of the library suggests to use methods like this to get an HTMLElement: var node = document.getElementById('my-node') but in my case I can't do something like this because my node isn't in the document.

So there's a way to convert a JSX.Element to an HTMLElement? Thanks in advance ;)

1 Answers

Use renderToStaticMarkup to do so.

import { renderToStaticMarkup } from "react-dom/server"

const output = document.createElement("div")
const staticElement = renderToStaticMarkup(reactElement))
output.innerHTML = `<div>${staticElement}</div>`
Related