How to use Page transitions in next.js #1711
-
Hello, Total noob here. I don't quite understand how the useTransition function works. This is how I am currently implementing it: import { useTransition, animated as a } from 'react-spring'
import useStore from '@/helpers/store'
const DOM = () => {
const router = useStore((s) => s.router)
const transitions = useTransition(router, {
key: null,
from: { opacitiy: 0, scale: 0, background: '#6f6f6f' },
enter: { opacity: 1, scale: 1, background: '#0f0f0f' },
leave: { opacity: 1, scale: 0 },
})
return (
<>
{transitions((style) => (
<a.div
className='absolute max-w-lg px-4 py-2 text-lg shadow-xl md:text-base top-8 left-1/2 text-gray-50 transform -translate-x-1/2'
style={style}
>
<h1>Page 2!</h1>
</a.div>
))}
</>
)
} https://codesandbox.io/s/next-spring-ch3cn?file=/src/pages/box.jsx 🙏 Edit: This Code Sandbox is using react transitions, but not next.js https://codesandbox.io/s/router-transitions-4j2q2 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
This would go in I can see you're using |
Beta Was this translation helpful? Give feedback.
-
Thanks @joshuaellis For completenes: import { useSpring, animated as a } from 'react-spring'
import { useEffect } from 'react'
const DOM = () => {
const router = useStore((s) => s.router)
const [transition, api] = useSpring(() => ({
from: { opacitiy: 0, scale: 0 },
to: { opacity: 1, scale: 1, background: '#0e0e0e' },
}))
useEffect(() => {
if (router) {
const handleRouteChange = (url, { shallow }) => {
console.log(
`App is changing to ${url} ${
shallow ? 'with' : 'without'
} shallow routing`
)
api.start({ opacity: 0, scale: 0 })
}
router.events.on('routeChangeStart', handleRouteChange)
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
console.log('Router Listener Unmounted')
router.events.off('routeChangeStart', handleRouteChange)
}
}
}, [])
return (
<>
<a.div
className='absolute max-w-lg px-4 py-2 text-lg shadow-xl md:text-base top-8 left-1/2 text-gray-50 transform -translate-x-1/2'
style={transition}
>
<h1>Page 2!</h1>
</a.div>
</>
)
} |
Beta Was this translation helpful? Give feedback.
This would go in
_app.js
in thepages
folder. Typically what i've done in the past for a basic fade in/out is have a div that covers the whole page that has an opacity 0 and the spring changes that to 1 through listening torouter events
. So onchangeStart
you would show the div covering the screen, onchangeComplete
you would hide it again giving the illusion the page faded out which is much simpler than trying to apply animated props correctly to the passedComponent
.I can see you're using
react-three-next
you might have more luck asking in that repo because it messes with theapp.js
file.