Skip to content

Commit 3e143ec

Browse files
Add AnimatePresence mode="wait" spec for a key change as the exit completes
Co-authored-by: Matt Perry <[email protected]>
1 parent 93d6f00 commit 3e143ec

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { AnimatePresence, motion } from "framer-motion"
2+
import { useRef, useState } from "react"
3+
4+
/**
5+
* mode="wait" where the key changes again at the moment the exiting child
6+
* finishes its exit, with no transitions involved.
7+
*/
8+
export const App = () => {
9+
const [count, setCount] = useState(0)
10+
const armed = useRef(false)
11+
12+
return (
13+
<div>
14+
<button
15+
id="next"
16+
onClick={() => {
17+
armed.current = true
18+
setCount(1)
19+
}}
20+
>
21+
next
22+
</button>
23+
<p id="state">{count}</p>
24+
<AnimatePresence mode="wait" initial={false}>
25+
<motion.div
26+
key={count}
27+
id={`child-${count}`}
28+
className="child"
29+
initial={{ opacity: 0 }}
30+
animate={{ opacity: 1 }}
31+
exit={{ opacity: 0 }}
32+
transition={{ duration: 0.1 }}
33+
onAnimationComplete={() => {
34+
if (count === 0 && armed.current) {
35+
armed.current = false
36+
setCount(2)
37+
}
38+
}}
39+
>
40+
{count}
41+
</motion.div>
42+
</AnimatePresence>
43+
</div>
44+
)
45+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
describe("AnimatePresence mode=wait: key changes as the exit completes", () => {
2+
it("renders the latest child", () => {
3+
cy.visit("?test=animate-presence-wait-exit-key-change")
4+
.wait(100)
5+
.get("#next")
6+
.click()
7+
.get("#state")
8+
.should("have.text", "2")
9+
.get(".child", { timeout: 2000 })
10+
.should(($children: any) => {
11+
expect($children.length).to.equal(1)
12+
expect($children[0].id).to.equal("child-2")
13+
expect(getComputedStyle($children[0]).opacity).to.equal("1")
14+
})
15+
})
16+
})

0 commit comments

Comments
 (0)