Skip to content

Commit 9241f1b

Browse files
Merge pull request #17 from poacher2k/master
Update README with advanced usage of `replace` method
2 parents 11770d9 + 6a664de commit 9241f1b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,44 @@ require('react-dom').render(reactElement, document.getElementById('root'));
118118
// <div><span style="font-size: 42px;">replaced!</span></div>
119119
```
120120

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

123161
```sh

0 commit comments

Comments
 (0)