Skip to content

Commit 27ed8b6

Browse files
committed
feat(types): add lib/dom-to-react declaration
1 parent 438b9af commit 27ed8b6

File tree

5 files changed

+56
-2
lines changed

5 files changed

+56
-2
lines changed

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@
6767
"files": [
6868
"dist",
6969
"lib",
70-
"types/index.d.ts"
70+
"types/index.d.ts",
71+
"types/lib"
7172
],
7273
"license": "MIT"
7374
}
File renamed without changes.

types/lib/dom-to-react.d.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import * as React from 'react';
2+
import { DomNode, HTMLReactParserOptions } from 'html-react-parser';
3+
4+
/**
5+
* Converts DOM nodes to React elements.
6+
* @returns ReactElement or and array of ReactElements.
7+
*/
8+
export default function domToReact(
9+
nodes: DomNode[],
10+
options?: HTMLReactParserOptions
11+
): React.ReactElement | React.ReactElement[];

types/lib/dom-to-react.test.tsx

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { HTMLReactParserOptions } from 'html-react-parser';
2+
import domToReact from 'html-react-parser/lib/dom-to-react';
3+
import * as React from 'react';
4+
import htmlToDOM from 'html-dom-parser';
5+
6+
/* $ExpectType ReactElement<any, string | ((props: any) => ReactElement<any, string | any | (new (props: any) => Component<any, any, any>)> | null) |
7+
(new (props: any) => Component<any, any, any>)> |
8+
ReactElement<any, string | ((props: any) => ReactElement<any, string | any | (new (props: any) => Component<any, any, any>)> | null) |
9+
(new (props: any) => Component<any, any, any>)>[] */
10+
domToReact(htmlToDOM('<div>text</div>'));
11+
12+
// `options.replace`
13+
14+
// Return React.createElement from `replace`
15+
domToReact(htmlToDOM('<p id="replace">text</p>'), {
16+
replace: domNode => {
17+
if (domNode.attribs && domNode.attribs.id === 'replace') {
18+
return React.createElement('span', {}, 'replaced');
19+
}
20+
}
21+
});
22+
23+
// Return ReactElement
24+
const options: HTMLReactParserOptions = {
25+
replace({ attribs }) {
26+
return attribs && attribs.id === 'remove' && <React.Fragment />;
27+
}
28+
};
29+
30+
domToReact(htmlToDOM('<p><br id="remove"></p>'), options);
31+
32+
// Return domhandler node
33+
domToReact(htmlToDOM('<a id="header" href="#">Heading</a>'), {
34+
replace: node => {
35+
if (node.attribs && node.attribs.id === 'header') {
36+
return {
37+
type: 'h1',
38+
props: { children: 'Heading' }
39+
};
40+
}
41+
}
42+
});

types/tsconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"noEmit": true,
1010
"jsx": "react",
1111
"baseUrl": ".",
12-
"paths": { "html-react-parser": ["."] },
12+
"paths": { "html-react-parser": ["."], "html-react-parser/*": ["./*"] },
1313
"moduleResolution": "node"
1414
}
1515
}

0 commit comments

Comments
 (0)