Skip to content

Commit 58f0575

Browse files
author
Daniel Skogly (poacher2k)
committed
Updates README with advanced usage of the replace method, keeping child
nodes that also gets parsed recursively.
1 parent ddd289b commit 58f0575

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

README.md

+38
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,44 @@ require('react-dom').render(reactElement, document.getElementById('root'));
122122
// <div><span style="font-size: 42px;">replaced!</span></div>
123123
```
124124

125+
Advanced usage with replace, keeping children (useful if child elements also needs to be replaced or just kept):
126+
127+
```js
128+
var Parser = require('html-react-parser');
129+
var domToReact = require('html-react-parser/lib/dom-to-react'); // used for recursively parsing DOM created from the HTML
130+
var React = require('react');
131+
132+
var html = '<div><p id="main"><span class="prettify">keep me and make me pretty!</span></p></div>';
133+
134+
var parserConfig = {
135+
replace: function(domNode) {
136+
var parsedChildren;
137+
if (domNode.attribs) {
138+
if (domNode.attribs.id === 'main') {
139+
parsedChildren = domToReact(domNode.children, parserConfig); // continue parsing domNode's children with same config
140+
return React.createElement('span', {
141+
style: { fontSize: '42px' }
142+
}, parsedChildren);
143+
// equivalent jsx syntax:
144+
// return <span style={{ fontSize: '42px' }}>{parsedChildren}</span>;
145+
} else if (domNode.attribs.class === 'prettify') {
146+
parsedChildren = domToReact(domNode.children, parserConfig); // continue parsing domNode's children with same config
147+
return React.createElement('span', {
148+
style: { color: 'hotpink' }
149+
}, parsedChildren);
150+
// equivalent jsx syntax:
151+
// return <span style={{ color: 'hotpink' }}>{parsedChildren}</span>;
152+
}
153+
}
154+
}
155+
};
156+
157+
var reactElement = Parser(html, parserConfig);
158+
159+
require('react-dom').render(reactElement, document.getElementById('root'));
160+
// <div><span style="font-size: 42px;"><span class="prettify" style="color: hotpink;">keep me and make me pretty!</span></span></div>
161+
```
162+
125163
## Testing
126164

127165
```sh

0 commit comments

Comments
 (0)