Repository navigation
Closed
Labels
bugSomething isn't working
Description
The following code gives two errors:
const options: HTMLReactParserOptions = {
replace: (domNode: DOMNode) => {
if (!(domNode instanceof Element)) return
if (domNode.name === 'a') {
domNode.attribs.target = '_blank'
domNode.attribs.rel = 'noopener noreferrer'
return domNode // error 1
}
if (['html', 'head', 'body'].includes(domNode.name)) {
return <>{domToReact(domNode.children, options)}</> // error 2
}
}
}
Error 1:
Type '(domNode: DOMNode) => Element | JSX.Element | undefined' is not assignable to type '(domNode: DOMNode) => string | boolean | void | Element | null'.
Type 'Element | JSX.Element | undefined' is not assignable to type 'string | boolean | void | Element | null'.
Type 'Element' is not assignable to type 'string | boolean | void | Element | null'.
Type 'Element' is missing the following properties from type 'ReactElement<any, any>': props, keyts(2322)
It seems HTMLReactParserOptions's replace expects JSX.Element instead of domhandler's Element
Error 2:
Argument of type 'ChildNode[]' is not assignable to parameter of type 'DOMNode[]'.
Type 'ChildNode' is not assignable to type 'DOMNode'.
Type 'CDATA' is not assignable to type 'DOMNode'.
Type 'CDATA' is missing the following properties from type 'Element': name, attribs, tagName, attributests(2345)
Expected Behavior
There's no type errors
Actual Behavior
Build fails.
Steps to Reproduce
Use the above code
Reproducible Demo
Environment
- Version: v5.0.0
- Platform: React & Vite
- Browser: Chrome
- OS: macOS
Keywords
Type error
Reacted by Amir H. Khanjani
Metadata
Metadata
Assignees
Labels
bugSomething isn't working
Activity
remarkablemark commentedon Oct 29, 2023
For the 1st error, can you return void since the return type should either be a React element or void (returning the domNode shouldn't really do anything):
For the 2nd error, can you use type assertion:
You can import
ElementandDOMNodefrom:harryzcy commentedon Oct 29, 2023
Thanks, the method works.
test(dom-to-react): assert replace with children
fix(types): add back `object` to `replace` option return type
remarkablemark commentedon Oct 29, 2023
I decided to add back the
objectreturn type forreplaceoption in order to fix error 1. See #1129docs(readme): document type error under v5
remarkablemark commentedon Oct 29, 2023
Release:
Fix type errors in html-react-parser v5
Bkumar48 commentedon Feb 26, 2024
` const options: HTMLReactParserOptions = {
replace: (domNode: DOMNode) => {
if (!(domNode instanceof Element)) return;
if (domNode.name === "ul") {
return (
{domToReact(domNode.children as DOMNode[])}
);
}
};`
Only first condition is getting replaced, can anyone help me with this?
remarkablemark commentedon Feb 26, 2024
@Bkumar48 can you open a new issue and provide a reproducible example?