← cd ../blog

html-react-parser: how to convert HTML to React

In one sentence

html-react-parser turns HTML into pieces of a page for React, a library for building web interfaces. It lets you reuse HTML that already exists without rewriting it by hand.

What it is and what it’s for

Imagine you have some HTML text that is already ready, for example one you received from another program or read from a database. In React you cannot simply insert it as it is.

Without a tool like this you have two options. The first is to rewrite everything by hand as React code, which is a long job. The second is to insert the text as it is, but then you cannot change a single link or a single image.

html-react-parser reads the HTML text and builds a tree of React elements. A tree is a structure where each piece can contain other pieces. Each piece, such as a link or a paragraph, is a node: you can decide what to do with it. The result is a set of React elements that are ready to insert into a page.

The project is a library: it does not start on its own. You connect it to your code and call it with parse(html, opzioni). The argument opzioni is an optional list of settings. You can also call it without options: in that case you get the React elements as they are, with no replacements.

The replace option receives each node and, if you want, replaces it with a React element of your own. It works both with Node.js and in the browser. With the trim option you can remove unnecessary spaces and line breaks.

A concrete example

Exercise: convert an HTML page saved in a file, replacing each link with the text followed by its address (URL), without losing lists and styles.

This is useful for someone who needs a printable or plain-text version of a page, without losing its structure. At the end you will have an HTML block where each link has become “Text (URL)” inside a span, a simple text container. Lists and the class and style attributes, that is the labels that give elements their name and appearance, stay in place.

What you’ll see in the terminal:

<div><ul class="menu">
  <li><span>Guida (https://example.com/guida)</span></li>
  <li><span>Contatti (https://example.com/contatti)</span></li>
</ul>
<p style="color:red">Vedi <span>FAQ (https://example.com/faq)</span>.</p>
</div>

Who it’s for (and who it isn’t)

Project card

What you need to try it, and what you DON’T need

You need a terminal, git, and Node.js with npm. You also need an internet connection, to download the project. Python is not needed: the project is written in TypeScript, but we will only use a small JavaScript file.

The project is downloaded from https://github.com/remarkablemark/html-react-parser: the first step of the guide downloads it with git.

You don’t need secret keys or an account. The guide does not use any external services, apart from GitHub and the website from which npm downloads packages.

Let’s try it step by step

Step 1: installation. We download the project, enter its folder, and switch to the version used in this guide. Then we install the dependencies, that is the other pieces of code that the project needs, and we build it.

Building, in jargon build, means preparing the files so they can be used. It is needed because the demo in step 2 uses the project in that prepared form.

Run these commands, one after the other:

Type in the terminal, from a folder of your choice:

git clone https://github.com/remarkablemark/html-react-parser.git
cd html-react-parser
git checkout 01d74670e00776df550742646eb87eac28c7609e
npm ci
npm run build

What you’ll see in the terminal (don’t type this: it’s only there for comparison):

Cloning into 'html-react-parser'...
Note: switching to '01d74670e00776df550742646eb87eac28c7609e'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this

Here you only see the first lines of the output: the rest is normal, and some lines are in English because the program writes them. What you should see: the expected lines are those of the clone, the checkout and the installation; how long the installation takes changes from one try to another.

It went well if the terminal shows no errors and gives you back the cursor for a new command. Npm may report vulnerabilities, that is security flaws, in the development dependencies.

Step 2: the demo. Here we do the exercise from the assignment: we convert a test page and check the result. We need two files in the same folder: the page to convert and the script that converts it. A script is a small program that you run from the terminal.

pagina.html contains a list with two links and a paragraph with a third link, colored with a style.

Create the file pagina.html, in the html-react-parser folder, with a text editor (not from the terminal), and paste this content into it:

<ul class="menu">
  <li><a href="https://example.com/guida">Guida</a></li>
  <li><a href="https://example.com/contatti">Contatti</a></li>
</ul>
<p style="color: red">Vedi <a href="https://example.com/faq">FAQ</a>.</p>

converti.mjs is the script: it reads pagina.html, replaces each link, and prints the result on screen.

Create the file converti.mjs, in the html-react-parser folder, with a text editor (not from the terminal), and paste this content into it:

import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import parse, { domToReact } from 'html-react-parser';
import { readFileSync } from 'node:fs';

const opzioni = {
  replace(nodo) {
    if (nodo.name === 'a') {
      const testo = domToReact(nodo.children, opzioni);
      return createElement('span', {}, testo, ' (' + nodo.attribs.href + ')');
    }
  },
};
console.log(renderToStaticMarkup(createElement('div', {}, parse(readFileSync('pagina.html', 'utf8'), opzioni))));

Now we run the script with Node.js:

Type in the terminal, from the html-react-parser folder:

node converti.mjs

What you’ll see in the terminal:

<div><ul class="menu">
  <li><span>Guida (https://example.com/guida)</span></li>
  <li><span>Contatti (https://example.com/contatti)</span></li>
</ul>
<p style="color:red">Vedi <span>FAQ (https://example.com/faq)</span>.</p>
</div>

What you should see: an HTML block with the list and the paragraph. It went well if each link appears as text followed by its address in brackets. The paragraph keeps its style, and the FAQ link inside the paragraph also becomes text plus its address.

What happened behind the scenes

The script reads pagina.html as text and passes it to parse.

The parser is the piece that reads a text and gets an ordered structure from it. It builds a tree of nodes: one for each piece of the HTML.

For each node, replace checks whether it is a link. The line if (nodo.name === 'a') { checks the name of the node: if it is a, the node is a link.

If it is a link, the line return createElement('span', {}, testo, ' (' + nodo.attribs.href + ')'); returns a new element. createElement is the React function that creates an element. The new element is a span with the text of the link and, in brackets, the value of href, that is the address. The original text is converted again, so it stays the same.

If the node is not a link, replace returns nothing and the node stays as it is.

Finally, renderToStaticMarkup turns the React elements into HTML text, and console.log prints it on screen.

The result keeps the list and the line <ul class="menu">. The style of the paragraph appears as color:red: React rewrites it without spaces.

This answers the assignment: each link has become text plus its address in a span, while lists and styles have stayed.

Things to keep in mind

Where to start reading the code

The first file to open is src/index.ts: it is short and contains the function you called in the demo.

Glossary

A note on the test

The procedure was tested on Debian 12 in WSL2 (Linux).