I have a React app that contains multiple tabs, which are lazy-loaded separate apps. The overarching app sets the tabs and the loaded apps have section anchors that can be navigated between tabs.
My issue is, as the anchors only load with the ImportedComponent
, the useEffect
cannot find the anchor with the first render, only subsequent renders. Any suggestions?
const Tab3 = () => {
useEffect(() => {
linkToComponentSection(anchor);
},
[anchor]);
return (
<ImportedComponent />
)
}
const ImportedComponent = () => {
return (
<>
<Title />
<a id={anchorLinkForTab3} />
</>
)
}
The only solution I have found is to wrap the contents of the useEffect in a setTimeout, which works but isn’t ideal.
I considered not using lazy loading but this also isn’t ideal.
2
Answers
The below is the hook that worked utilising
MutationObserver
:I would try to solve this with a MutationObserver.
When the observer detects that the content of the tab has changed you can execute your callback to navigate/scroll/jump to the anchor.
(I have not tried this before; but I sucessfully wrapped both ResizeObserver and IntersectionObserver in custom react hooks and use them ever since.)