Skip to content

Commit

Permalink
Adding initial option to useInView (#3050)
Browse files Browse the repository at this point in the history
* Adding initial option to useInView

* Change initial value
  • Loading branch information
mattgperry authored Feb 6, 2025
1 parent b38f86f commit 88f36d2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RefObject } from "../../../utils/safe-react-types"
import { TargetAndTransition } from "../../../types"
import { RefObject } from "../../../utils/safe-react-types"
import { VariantLabels } from "../../types"

export type ViewportEventHandler = (
Expand Down
26 changes: 25 additions & 1 deletion packages/framer-motion/src/utils/__tests__/use-in-view.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { act, useEffect, useRef } from "react"
import { render } from "../../../jest.setup"
import { act, useRef, useEffect } from "react"
import { useInView } from "../use-in-view"
import { getActiveObserver } from "./mock-intersection-observer"

Expand Down Expand Up @@ -34,6 +34,30 @@ describe("useInView", () => {
expect(results).toEqual([false])
})

test("Can change initial value", () => {
const results: boolean[] = []

const Component = () => {
const ref = useRef(null)
const isInView = useInView(ref, { initial: true })

useEffect(() => {
if (results[results.length - 1] !== isInView)
results.push(isInView)
}, [isInView])

return <div ref={ref} />
}

const { rerender } = render(<Component />)
rerender(<Component />)
rerender(<Component />)
rerender(<Component />)
rerender(<Component />)

expect(results).toEqual([true])
})

test("Returns true when element enters the viewport", async () => {
const results: boolean[] = []

Expand Down
11 changes: 9 additions & 2 deletions packages/framer-motion/src/utils/use-in-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@ export interface UseInViewOptions
root?: RefObject<Element | null>
once?: boolean
amount?: "some" | "all" | number
initial?: boolean
}

export function useInView(
ref: RefObject<Element | null>,
{ root, margin, amount, once = false }: UseInViewOptions = {}
{
root,
margin,
amount,
once = false,
initial = false,
}: UseInViewOptions = {}
) {
const [isInView, setInView] = useState(false)
const [isInView, setInView] = useState(initial)

useEffect(() => {
if (!ref.current || (once && isInView)) return
Expand Down

0 comments on commit 88f36d2

Please sign in to comment.