I have some issue in implementing routing as expected.
My scenario here is I have a component, content inside the component is get from the json data in server. In the content there are some <a>
tags, when I click on the link, page is reloading instead of how actual routing works.
what I have tried is
import React, {Component} from 'react'
............. other imports ....
const htmlContent=`<div>
<p> Lorem ipsum content goes here </p>
<a href="/home">Home</a>
</div>`;
export class InnerPage extends Component{
...... other stuffs .......
render(){
return(
<div>
// static content
<div dangerouslySetInnerHTML={{__html: htmlContent}} />
</div>
)
}
}
Here it renders the html content as expected, but the routing is not working as expected. Any help will be appreciated.
The best way to handle this is to add an event listener to the anchor element on the html content. On click event, get the href value and then use the value to make route change.
Sample code
<div>
// static content
<div ref={dynamic_content} dangerouslySetInnerHTML={{__html: htmlContent}} />
</div>
Function:
const handleAnchorClick=(event)=>{
event.preventDefault();
const path = event.target.href;
//Put the redirect here with react route
}
//Add this in the useEffect hook once the content is loaded
useEffect(()=>{
if(dynamic_content.current){
dynamic_content.current.getElementByTag('a').addEventListener('click', handleAnchorClick)
}
//Remove the eventlistener on component unmount
},[htmlContent])