I receive HTML from the server that needs to be injected via dangerouslySetInnerHTML. After inserting the HTML I want to get a DOM element with id: home_content.
This is because I migrate from a legacy application(server-side rendered HTML) to React, the legacy application returns HTML. The goal of this React component is to parse the HTML from the legacy application to a React component. Within this component, I want to add React components to the initial HTML structure received from the server.
export default function App() {
const [data, setData] = useState({});
const [isLoading, setIsLoading] = useState(true);
const didMountRef = useRef(false);
const pageName = useSetPageTitle();
// Will be replaced by the actual API call, Add to legacy component
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
`http://127.0.0.1:8000/nav?action=${pageName}`
);
const legacyHTML = await response.text();
setData(legacyHTML);
setIsLoading(false);
};
fetchData();
didMountRef.current = true;
}, [pageName]);
useEffect(() => {
if(didMountRef.current) {
const domContainer = document.querySelector("#home_content");
ReactDOM.render(<LikeButton />, domContainer);
}
}, [didMountRef]);
return (
<>
<LegacyDependencies />
<div>
<div id="content"></div>
{isLoading ? (
<div>
<span>loading...</span>
</div>
) : (
<div
dangerouslySetInnerHTML={{
__html: data,
}}
/>
)}
</div>
</>
);
}
I receive the following error: Error: Target container is not a DOM element.
Is it possible to add a React component to HTML inserted by dangerouslySetInnerHTML?
dangerouslySetInnerHTML