score:1

Accepted answer

I think the idea would be to use an effect to scroll to the appropriate component after the component mounts. Perhaps something like this:

React.useEffect(() => {
    const anchor = window.location.hash.slice(1);
    if (anchor) {
        const anchorEl = document.getElementById(anchor);
        if (anchorEl) {
            anchorEl.scrollIntoView();
        }
    }
}, []);

Notes:

  • I haven't tested this.
  • useLayoutEffect instead of useEffect may give a better experience here; see this article for details.
  • I'm bypassing React and using the DOM. I usually try to avoid that, but since this logic is isolated and inherently focused on browser DOM behavior, I think this is a good use case for it (instead of complicating the code by pulling in more interactions with your React components.)
  • scrollIntoView is convenient but experimental; consider using the scroll-into-view-if-needed NPM package instead.

score:0

I don't know if I understand correctly.

I think, you should make a function for wait everything complete.

but, if you can't catch exactly timing when everything fine, you can use trick.

example :

    const CategoryDisplay: React.FC<Props> = (props) => {
        ...
        const [accordionId, setAccordionId] = useState("");
        useEffect(()=>{
          // this component mounted
          ...
          setTimeout(()=>{
            // do something
            setAccordionId(`category-${accordion.id}`);
          },0);
        }, []);
        return (
          <>
            <Accordion
              id={accordionId}/>
          </>
        );
    };

This will definitely run in the frame after the component mounted.


Related Query

More Query from same tag