html-react-parser: Replace DOM Node with another DOM Node containing inner text child (A-link)

3.9k Views Asked by At

Using html-react-parser, I need to output my string as JSX, but with the replacement of all <a href=...> to the encapsulating new element <LinkContainer to={href}><a>..</a></LinkContainer> which will contain the <a>. In other words, I'm wrapping my A-links in a LinkContainer tag.

The problem is, I don't know how to express the Inner Text of the A-tag I'm replacing, which has to be included:

parse(successMessage, { 
        replace: domNode => {
            if (domNode.attribs && domNode.attribs.href) {
                return <LinkContainer to={domNode.attribs.href}><a href="#">How to get the Inner Text?</a></LinkContainer>;
            }  
        }}
    );

Nothing like innerText or text is available. The DOM Nodes that come to me are

  • The A-tag itself
  • Its child, which is inner text, a separate node
1

There are 1 best solutions below

0
On BEST ANSWER

I found the solution. You can just replace the A-tag and get the link's text from domNode.children[0].data.

    parse(successMessage, { 
            replace: domNode => {
                if (domNode.attribs && domNode.attribs.href) {
                    return <LinkContainer to={domNode.attribs.href}><a href="#">{domNode.children[0].data}</a></LinkContainer>;
                }  
            }}
        )