in my React app I am getting some HTML from another server (Wikipedia) and - in this text - want to replace all the links with react-router links.
What I have come up with is the following code:
// Parse HTML with JavaScript DOM Parser
let parser = new DOMParser();
let el = parser.parseFromString('<div>' + html + '</div>', 'text/html');
// Replace links with react-router links
el.querySelectorAll('a').forEach(a => {
let to = a.getAttribute('href');
let text = a.innerText;
let link = <Link to={to}>{text}</Link>;
a.replaceWith(link);
});
this.setState({
html: el.innerHTML
})
Then later in render()
I then inserted it into the page using
<div dangerouslySetInnerHTML={{__html: this.state.html}} />
The problem is that React JSX is not a native JavaScript element thus not working with replaceWith
. I also assume that such a Link
object can not be stored as text and then later be restored using dangerouslySetInnerHTML
.
So: what is the best way to do this method? I want to keep all the various elements around the link so I cannot simply loop through the links in render()