Skip to content

Update README with advanced usage of replace method #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 30, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,44 @@ require('react-dom').render(reactElement, document.getElementById('root'));
// <div><span style="font-size: 42px;">replaced!</span></div>
```

Advanced usage with replace, keeping children (useful if child elements also needs to be replaced or just kept):

```js
var Parser = require('html-react-parser');
var domToReact = require('html-react-parser/lib/dom-to-react'); // used for recursively parsing DOM created from the HTML
var React = require('react');

var html = '<div><p id="main"><span class="prettify">keep me and make me pretty!</span></p></div>';

var parserConfig = {
replace: function(domNode) {
var parsedChildren;
if (domNode.attribs) {
if (domNode.attribs.id === 'main') {
parsedChildren = domToReact(domNode.children, parserConfig); // continue parsing domNode's children with same config
return React.createElement('span', {
style: { fontSize: '42px' }
}, parsedChildren);
// equivalent jsx syntax:
// return <span style={{ fontSize: '42px' }}>{parsedChildren}</span>;
} else if (domNode.attribs.class === 'prettify') {
parsedChildren = domToReact(domNode.children, parserConfig); // continue parsing domNode's children with same config
return React.createElement('span', {
style: { color: 'hotpink' }
}, parsedChildren);
// equivalent jsx syntax:
// return <span style={{ color: 'hotpink' }}>{parsedChildren}</span>;
}
}
}
};

var reactElement = Parser(html, parserConfig);

require('react-dom').render(reactElement, document.getElementById('root'));
// <div><span style="font-size: 42px;"><span class="prettify" style="color: hotpink;">keep me and make me pretty!</span></span></div>
```

## Testing

```sh
Expand Down