Samuele Rizzo
Samuele Rizzo

Reputation: 213

Convert a JSX.Element to an HTMLElement

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 ;)

Upvotes: 18

Views: 34552

Answers (2)

Amin Ya
Amin Ya

Reputation: 1908

To do that, use renderToStaticMarkup from the react-dom/server library.

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

const output = document.createElement('p')
const staticElement = renderToStaticMarkup(reactElement)
output.innerHTML = staticElement

Upvotes: 20

DevAttendant
DevAttendant

Reputation: 636

Question might be old, but while looking for a solution for this I found an elegant way to render a hidden element as an image.

render() {
    return (
        <div>
            <div
                id="image-template"
                className="d-none"
                style={{
                    width: "200px",
                    height: "200px",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "white",
                    fontSize: "10px",
                    textAlign: "center",
                    backgroundColor: "green",
                }}
            >
                <span style={{ margin: "20px" }}>{"Hey, an image rendered but not visible!"}</span>
            </div>
        </div>
    );
}

With the class d-none (from bootstrap) the element is hidden to the user, so it does not matter where you place it. d-none in bootstrap is basically display: none !important;.

Now add a function to create an image:

async createImage() {
    const template = document.getElementById("image-template").cloneNode(true);
    template.classList.remove("d-none");

    const base64Image = await htmlToImage.toPng(template, {
        height: 200,
        width: 200,
    });
    // Do whatever you want to do with your image
}

The element is cloned and the d-none/display: none removed to be able to render it with htmlToImage. The result is the base64 data you can use whereever you want.

Upvotes: 0

Related Questions