Skip to content

Commit e3c91ac

Browse files
Update README with better documentation on replace method
Add new parameter `key` and update examples.
1 parent 226cc15 commit e3c91ac

File tree

1 file changed

+35
-14
lines changed

1 file changed

+35
-14
lines changed

README.md

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,36 @@ ReactDOM.render(
6868

6969
### Options
7070

71-
#### replace(domNode)
71+
#### replace(domNode, key)
7272

73-
`replace` allows you to swap an element with your own React element.
73+
The `replace` method allows you to swap an element with your own React element.
7474

75-
The `domNode` object has the same schema as the output from [htmlparser2.parseDOM](https://github.com/fb55/domhandler#example).
75+
The method has 2 parameters:
76+
1. `domNode`: An object which shares the same schema as the output from [htmlparser2.parseDOM](https://github.com/fb55/domhandler#example).
77+
2. `key`: A number to keep track of the element. You should set it as the ["key" prop](https://fb.me/react-warning-keys) in case your element has siblings.
78+
79+
```js
80+
Parser('<p id="replace">text</p>', {
81+
replace: function(domNode, key) {
82+
console.log(domNode);
83+
// { type: 'tag',
84+
// name: 'p',
85+
// attribs: { id: 'replace' },
86+
// children: [],
87+
// next: null,
88+
// prev: null,
89+
// parent: null }
90+
91+
console.log(key); // 0
92+
93+
return;
94+
// element is not replaced because
95+
// a valid React element is not returned
96+
}
97+
});
98+
```
99+
100+
Working example:
76101

77102
```js
78103
var Parser = require('html-react-parser');
@@ -81,18 +106,14 @@ var React = require('react');
81106
var html = '<div><p id="main">replace me</p></div>';
82107

83108
var reactElement = Parser(html, {
84-
replace: function(domNode) {
85-
// example `domNode`:
86-
// { type: 'tag',
87-
// name: 'p',
88-
// attribs: { id: 'main' },
89-
// children: [],
90-
// next: null,
91-
// prev: null,
92-
// parent: [Circular] }
109+
replace: function(domNode, key) {
93110
if (domNode.attribs && domNode.attribs.id === 'main') {
94-
// element is replaced only if a valid React element is returned
95-
return React.createElement('span', { style: { fontSize: '42px' } }, 'replaced!');
111+
return React.createElement('span', {
112+
key: key,
113+
style: { fontSize: '42px' } },
114+
'replaced!');
115+
// equivalent jsx syntax:
116+
// return <span key={key} style={{ fontSize: '42px' }}>replaced!</span>;
96117
}
97118
}
98119
});

0 commit comments

Comments
 (0)