score:7
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.
Source: stackoverflow.com
Related Query
- How to Navigate and Scroll to an Element with ID in a Next.js Page wrapped with AnimatePresence
- How to navigate to another page with a smooth scroll on a specific id with react router and react scroll
- How to stick title of scrollable content and when the content gets over title too should scroll and then happens with next scroll content
- How can I use scroll into view from different/other page with react and redux?
- How to scroll to an element with hooks/functions?
- How to nest Scene and navigate with direction='vertical' in React Native Router Flux?
- How can I make my input field prefilled with data and editable on page load?
- how can injection dynamic html element to page with next.js?
- How to fetch data on page load and then on button click with useEffect
- Scroll to element on page load with React Hooks
- How to send POST and refresh page with React?
- How to check if parent element include children with spesific class with useEffect and UseRef?
- How can I specify authentication globally instead of defining on every page in Next js, I am using next-auth package with react query
- How to start at the bottom of a page and scroll upwards in reactJS
- How to use react-redux with next js and class components
- How to add event listener to the div element accessed with ref using react and typescript?
- How to drag and drop canvas web element with selenium in chrome
- How to style material ui next components with styled components and SASS
- How to add active class to link with current page and locale?
- How to scroll with mouse wheel and keyboard on vertical slider in echarts?
- How to pass a variable with text and a link into a React element
- selected element move up and down, but scroll behavior is not working with
- How to add html i tag with next and previous button in react-pagination package
- Gatsby syncing the table of contents with the page scroll and style the active link
- How to change the state when going to previous or next page with React?
- How can i use useParams() with an onClick button to navigate to different pages and display the data in react.js?
- How to communicate with Shopify Storefront and add JS snippet to Product Page
- How to open new page and scroll to id leaving the URL unaffected?
- How can I shuffle an array of objects on page render and map over the shuffled array without console warning of "two children with the same key"?
- How to go to another page without keeping scroll position with React
More Query from same tag
- React - uncallable expression
- Where to get props and set props in a functional component in React Js?
- Despite adding a unique key, react is throwing a warning
- Promise.all in Redux action and update state
- Select category in the form using select
- Searching for Webpack config for React Components Library with Typescript, SASS & CSS Modules via SASS support
- Set PlaceHolder color of a textarea dynamically in React
- Is there any chance to pass query params as like ?id="idValue" in route?
- React, Jest, Enzyme how to pass test App.js with store redux
- React Deleting checkbox item from list, strange behavior
- How to return the user's status within AWS's user pool using Amplify with Javascript?
- Toggle class only on one element, react js
- Toggle to display separately
- Create react app with npx that uses classes and not hooks
- Updating string in redux store
- How to move Cancel button to the right in IonSearchbar in Ionic React
- How to hide columns for which rows do not hold any data in devextreme react grid?
- How do I retrieve the error message from an API request
- JEST to test react components
- Styled-components and react-icons <IconContext.Provider> component
- Not able to display the data stored in a state object in react
- How can I access data attribute value using useRef hook?
- How to group an array of dynamic objects based on an a property value in react js / javascript
- Can't load content "Nothing was returned from render"
- Cant seem to access object property in array
- Displaying the Sum of values in React JSX
- React can't set state with hooks in useEffect()
- Material-UI: How to specify maxWidth of Chip?
- warn Non-deterministic routing danger: Attempting to create page: [...] already exists
- Framer motion modal - Animate presence does not work