@@ -122,6 +122,44 @@ require('react-dom').render(reactElement, document.getElementById('root'));
122
122
// <div><span style="font-size: 42px;">replaced!</span></div>
123
123
```
124
124
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
+
125
163
## Testing
126
164
127
165
``` sh
0 commit comments