score:7

Accepted answer

the culprit is the exitbeforeenter prop on on animatepresence. removing the prop fixes the hash id navigation but breaks some of my use-case.

if set to true, animatepresence will only render one component at a time. the exiting component will finish its exit animation before the entering component is rendered. - framer-motion docs

i couldn't just remove the exitbeforeenter prop as i had included it to fix a bug i had where targeting a node in the entering page collided with the identical one in the old instance of the exiting page. for example a ref logic on an animated svg header in the exiting page colliding with the entering page's header svg ref logic.

to get the best of both worlds, using the onexitcomplete that "fires when all exiting nodes have completed animating out", i passed it a callback that checks for the hash from the widow.location.hash and smooth scrolls to the id using scrollintoview note: onexitcomplete is only effective if exitbeforeenter prop is true.

// pages/_app.tsx
import { appprops } from 'next/app';
import { userouter } from 'next/router';
import { animatepresence } from 'framer-motion';

// the handler to smoothly scroll the element into view
const handexitcomplete = (): void => {
  if (typeof window !== 'undefined') {
    // get the hash from the url
    const hashid = window.location.hash;

    if (hashid) {
      // use the hash to find the first element with that id
      const element = document.queryselector(hashid);

      if (element) {
        // smooth scroll to that elment
        element.scrollintoview({
          behavior: 'smooth',
          block: 'start',
          inline: 'nearest',
        });
      }
    }
  }
};

const myapp = ({ component, pageprops }: appprops): jsx.element => {
  const router = userouter();
  return (
    <animatepresence exitbeforeenter onexitcomplete={handexitcomplete}>
      <component {...pageprops} key={router.route} />
    </animatepresence>
  );
};

export default myapp;


live codesandbox here.

ps: for some reason the the window.location.hash in the sandbox preview is always an empty string, breaking the hash navigation but opening the preview in a separate browser tab works like a charm.


Related Query

More Query from same tag