I'd like to implement a simple transition between two components using react-string
. My current attempt is at https://codesandbox.io/s/react-spring-simple-transition-16qhf?file=/src/App.tsx:
import React, { useState } from 'react'
import { useTransition, animated } from '@react-spring/web'
export default function App() {
const [page, setPage] = useState(1)
const transitions = useTransition(page, {
key: page,
initial: { opacity: 1 },
from: { opacity: 0, position: 'absolute' as const },
enter: { opacity: 1, position: 'relative' as const },
leave: { opacity: 0, position: 'absolute' as const },
config: { duration: 1000 },
})
return (
<div>
<h1>Page Title</h1>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ratione incidunt atque est sunt deleniti esse adipisci
quibusdam et enim alias accusantium, itaque beatae voluptates, ex illo harum repudiandae veniam inventore.
</p>
<div style={{ position: 'relative' }}>
{transitions((styles, item) => {
return item === 1 ? (
<animated.div style={styles}>
<h1>This is page 1</h1>
<button type="button" onClick={() => setPage(2)}>
Go to page 2
</button>
</animated.div>
) : (
<animated.div style={styles}>
<h1>This is page 2</h1>
<button type="button" onClick={() => setPage(1)}>
Go back to page 1
</button>
</animated.div>
)
})}
</div>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ratione incidunt atque est sunt deleniti esse adipisci
quibusdam et enim alias accusantium, itaque beatae voluptates, ex illo harum repudiandae veniam inventore.
</p>
</div>
)
}
This is what I expect/want to happen:
- Clicking "Go to page 2" will fade the page 1 component out over the span of 1 second.
- After page 1 has reached an opacity of
0
, it will unmount, and at the same time page 2 will mount with an opacity of0
(to prevent an empty space between the two paragraphs). - Page 2 will then fade in over the span of 1 second.
- Clicking "Go back to page 1" should perform the same steps as above, with the components reversed, of course.
I'm not sure why this isn't working as expected for me. The animation causes the component fading out to jump down slightly, and the other component is already starting to fade in while the first one is still fading out.