repl.it
@remarkablemark/

html-react-parser replace example

Nodejs

https://github.com/remarkablemark/html-react-parser#replacedomnode

fork
loading
Files
  • index.js
  • Packager files
  • package.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * @see https://github.com/remarkablemark/html-react-parser#replacedomnode
 */
const React = require('react');
const { renderToStaticMarkup } = require('react-dom/server');
const parse = require('html-react-parser');
const { domToReact } = require('html-react-parser');

const html = `
  <p id="main">
    <span class="prettify">
      keep me and make me pretty!
    </span>
  </p>
`;

const options = {
  replace: ({ attribs, children }) => {
    if (!attribs) return;

    if (attribs.id === 'main') {
      return React.createElement(
        'h1',
        { style: { fontSize: 42 } },
        domToReact(children, options)
      );
    }

    if (attribs.class === 'prettify') {
      return React.createElement(
        'span',
        { style: { color: 'hotpink' } },
        domToReact(children, options)
      );
    }
  }
};

console.log(renderToStaticMarkup(parse(html, options)));