Convert HTML element or document into Image in React

Today we will show you how to convert HTML element or document into Image in React. Sometimes you may need to download an Image of an element so here you will learn easy steps to convert document into Image using NPM Package.

Demo Application

In this example, we’ll convert div base HTML element into image and download it on button click.

Output - Convert HTML element or document into Image in React - Clue Mediator
Output – Convert HTML element or document into Image in React – Clue Mediator

Steps to convert HTML element into Image in React

  1. Create React application
  2. Install NPM dependency
  3. Design component
  4. Use the package to convert HTML into image
  5. Output

1. Create React application

Let’s create a react application using create-react-app. Run the following command to create a React App.

2. Install NPM dependency

Here, we will use the html-to-image npm package to convert HTML into Image. Run the following command to install the dependency.

3. Design component

Now, let’s simply design the React component as mentioned below.

App.js

Let’s design the component using the following style.

index.css

4. Use the package to convert HTML into image

Import the html-to-image npm package in the App.js component. Use the .toPng() method where you have to pass the reference of the DOM element and get the image in base64 string format.

Refer the following articles to download or open image in new tab.

5. Output

Put all code together and see how it looks.

App.js

Let’s run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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