Product
Introducing Java Support in Socket
We're excited to announce that Socket now supports the Java programming language.
html-to-react
Advanced tools
A lightweight library that converts raw HTML to a React DOM structure.
The html-to-react npm package is a utility that allows you to convert raw HTML strings into React components. This can be particularly useful for rendering HTML content dynamically in a React application.
Basic HTML to React Conversion
This feature allows you to convert a simple HTML string into a React element. The `HtmlToReact.Parser` class is used to parse the HTML string and convert it into a React component.
const HtmlToReact = require('html-to-react');
const htmlToReactParser = new HtmlToReact.Parser();
const html = '<div>Hello, <strong>world</strong>!</div>';
const reactElement = htmlToReactParser.parse(html);
Custom Processing Instructions
This feature allows you to define custom processing instructions to handle specific HTML tags in a custom way. In this example, all `div` elements are given a custom class name.
const HtmlToReact = require('html-to-react');
const htmlToReactParser = new HtmlToReact.Parser();
const processingInstructions = [
{
shouldProcessNode: function (node) {
return node.name && node.name === 'div';
},
processNode: function (node, children, index) {
return React.createElement('div', { key: index, className: 'custom-div' }, children);
}
}
];
const html = '<div>Hello, <strong>world</strong>!</div>';
const reactElement = htmlToReactParser.parseWithInstructions(html, () => true, processingInstructions);
Handling Complex HTML Structures
This feature demonstrates the ability to handle more complex HTML structures, such as nested elements. The parser can convert nested HTML elements into nested React components.
const HtmlToReact = require('html-to-react');
const htmlToReactParser = new HtmlToReact.Parser();
const html = '<div><p>Paragraph 1</p><p>Paragraph 2</p></div>';
const reactElement = htmlToReactParser.parse(html);
The react-html-parser package is another utility for converting HTML strings into React components. It offers similar functionality to html-to-react but with a simpler API. It is particularly useful for straightforward HTML to React conversions without the need for custom processing instructions.
The html-react-parser package is a highly performant library for converting HTML strings into React components. It supports custom processing instructions and is known for its speed and efficiency. It is a good alternative to html-to-react for performance-critical applications.
The react-dom-parser package allows you to parse HTML strings and convert them into React elements. It provides a flexible API for handling various HTML structures and is comparable to html-to-react in terms of functionality and ease of use.
A lightweight library that converts raw HTML to a React DOM structure.
I had a scenario where an HTML template was generated by a different team, yet I wanted to leverage React for the parts I did have control over. The template basically contains something like:
<div class="row">
<div class="col-sm-6">
<div data-report-id="report-1">
<!-- A React component for report-1 -->
</div>
</div>
<div class="col-sm-6">
<div data-report-id="report-2">
<!-- A React component for report-2 -->
</div>
</div>
</div>
I had to replace each <div>
that contains a data-report-id
attribute with an actual report,
which was nothing more than a React component.
Simply replacing the <div>
elements with a React component would end up with multiple top-level
React components that have no common parent.
The html-to-react module solves this problem by parsing each DOM element and converting it to a React tree with one single parent.
$ npm install --save html-to-react
The following example parses each node and its attributes and returns a tree of React elements.
const ReactDOMServer = require('react-dom/server');
const HtmlToReactParser = require('html-to-react').Parser;
const htmlInput = '<div><h1>Title</h1><p>A paragraph</p></div>';
const htmlToReactParser = new HtmlToReactParser();
const reactElement = htmlToReactParser.parse(htmlInput);
const reactHtml = ReactDOMServer.renderToStaticMarkup(reactElement);
assert.equal(reactHtml, htmlInput); // true
If certain DOM nodes require specific processing, for example if you want to capitalize each
<h1>
tag, the following example demonstrates this:
const ReactDOMServer = require('react-dom/server');
const HtmlToReact = require('html-to-react');
const HtmlToReactParser = require('html-to-react').Parser;
const htmlInput = '<div><h1>Title</h1><p>Paragraph</p><h1>Another title</h1></div>';
const htmlExpected = '<div><h1>TITLE</h1><p>Paragraph</p><h1>ANOTHER TITLE</h1></div>';
const isValidNode = function () {
return true;
};
// Order matters. Instructions are processed in the order they're defined
const processNodeDefinitions = new HtmlToReact.ProcessNodeDefinitions();
const processingInstructions = [
{
// Custom <h1> processing
shouldProcessNode: function (node) {
return node.parent && node.parent.name && node.parent.name === 'h1';
},
processNode: function (node, children) {
return node.data.toUpperCase();
}
},
{
// Anything else
shouldProcessNode: function (node) {
return true;
},
processNode: processNodeDefinitions.processDefaultNode
}
];
const htmlToReactParser = new HtmlToReactParser();
const reactComponent = htmlToReactParser.parseWithInstructions(htmlInput, isValidNode,
processingInstructions);
const reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
assert.equal(reactHtml, htmlExpected);
There may be a situation where you want to replace the children of an element with a React component. This is beneficial if you want to:
Below is a simple template that could get loaded via ajax into your application
<div class="row">
<div class="col-sm-6">
<div data-container="wysiwyg">
<h1>Sample Heading</h1>
<p>Sample Text</p>
</div>
</div>
</div>
You may want to extract the inner html from the data-container
attribute, store it and then pass
it as a prop to your injected RichTextEditor
.
<div class="row">
<div class="col-sm-6">
<div data-container="wysiwyg">
<RichTextEditor html={"<h1>Sample heading</h1><p>Sample Text</p>"} />
</div>
</div>
</div>
In your instructions object, you must specify replaceChildren: true
.
const React = require('react');
const HtmlToReact = require('html-to-react');
const HtmlToReactParser = require('html-to-react').Parser;
const htmlToReactParser = new HtmlToReactParser();
const htmlInput = '<div><div data-test="foo"><p>Text</p><p>Text</p></div></div>';
const htmlExpected = '<div><div data-test="foo"><h1>Heading</h1></div></div>';
const isValidNode = function () {
return true;
};
const processNodeDefinitions = new HtmlToReact.ProcessNodeDefinitions();
// Order matters. Instructions are processed in
// the order they're defined
const processingInstructions = [
{
// This is REQUIRED, it tells the parser
// that we want to insert our React
// component as a child
replaceChildren: true,
shouldProcessNode: function (node) {
return node.attribs && node.attribs['data-test'] === 'foo';
},
processNode: function (node, children, index) {
return React.createElement('h1', {key: index,}, 'Heading');
}
},
{
// Anything else
shouldProcessNode: function (node) {
return true;
},
processNode: processNodeDefinitions.processDefaultNode,
},
];
const reactComponent = htmlToReactParser.parseWithInstructions(
htmlInput, isValidNode, processingInstructions);
const reactHtml = ReactDOMServer.renderToStaticMarkup(
reactComponent);
assert.equal(reactHtml, htmlExpected);
There may be situations where you want to preprocess nodes before rendering them, analogously to the custom processing instructions functionality. The rationale for supporting preprocessing hooks is generally that you might want to apply more general processing to nodes, before applying custom processing hooks to filtered sets of nodes. You could accomplish the same by calling common functions from your custom processing hooks, but the preprocessing hooks API makes it more convenient.
Below is a simple template in which you may want to replace div IDs, via a preprocessing hook:
<div class="row">
<div id="first" data-process="shared">
<p>Sample For First</p>
</div>
<div id="second" data-process="shared">
<p>Sample For Second</p>
</div>
</div>
We want to process the above HTML into the following:
<div class="row">
<h1 id="preprocessed-first">First</h1>
<h2 id="preprocessed-second">Second</h2>
</div>
We can accomplish that with the following script, using a combination of preprocessing and custom processing instructions:
const React = require('react');
const HtmlToReact = require('html-to-react');
const HtmlToReactParser = require('html-to-react').Parser;
const htmlToReactParser = new HtmlToReactParser();
const htmlInput = '<div class="row">' +
'<div id="first" data-process="shared">' +
'<p>Sample For First</p>' +
'</div>' +
'<div id="second" data-process="shared">' +
'<p>Sample For Second</p>' +
'</div>' +
'</div>';
const htmlExpected = '<div class="row">' +
'<h1 id="preprocessed-first">First</h1>' +
'<h2 id="preprocessed-second">Second</h2>' +
'</div>';
const isValidNode = function () {
return true;
};
const preprocessingInstructions = [
{
shouldPreprocessNode: function (node) {
return node.attribs && node.attribs['data-process'] === 'shared';
},
preprocessNode: function (node) {
node.attribs = {id: `preprocessed-${node.attribs.id}`,};
},
}
];
const processNodeDefinitions = new HtmlToReact.ProcessNodeDefinitions();
const processingInstructions = [
{
shouldProcessNode: function (node) {
return node.attribs && node.attribs.id === 'preprocessed-first';
},
processNode: function(node, children, index) {
return React.createElement('h1', {key: index, id: node.attribs.id,}, 'First');
},
},
{
shouldProcessNode: function (node) {
return node.attribs && node.attribs.id === 'preprocessed-second';
},
processNode: function (node, children, index) {
return React.createElement('h2', {key: index, id: node.attribs.id,}, 'Second');
},
},
{
shouldProcessNode: function (node) {
return true;
},
processNode: processNodeDefinitions.processDefaultNode,
},
];
const reactComponent = parser.parseWithInstructions(htmlInput, isValidNode, processingInstructions,
preprocessingInstructions);
const reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);
assert.equal(reactHtml, htmlExpected);
Test locally: $ npm test
Test with coverage and report coverage to Coveralls: $ npm run test-coverage
Test with coverage and open HTML report: $ npm run test-html-coverage
FAQs
A lightweight library that converts raw HTML to a React DOM structure.
The npm package html-to-react receives a total of 353,689 weekly downloads. As such, html-to-react popularity was classified as popular.
We found that html-to-react demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
We're excited to announce that Socket now supports the Java programming language.
Security News
Socket detected a malicious Python package impersonating a popular browser cookie library to steal passwords, screenshots, webcam images, and Discord tokens.
Security News
Deno 2.0 is now available with enhanced package management, full Node.js and npm compatibility, improved performance, and support for major JavaScript frameworks.