motiondivision / motion

A modern animation library for React and JavaScript
https://motion.dev
MIT License
25.66k stars 843 forks source link

[BUG] codesandbox Reorder examples deprecated onChange in useRaisedShadow (code replacement suggestion) #2805

Open simon5454 opened 2 months ago

simon5454 commented 2 months ago

1. Describe the bug

The examples use a deprecated function "onChange".

2. IMPORTANT: Provide a CodeSandbox reproduction of the bug

From the documentation section "Reorder", the following examples use the deprecated "onChange".

https://codesandbox.io/p/sandbox/framer-motion-5-drag-to-reorder-lists-forked-n27v5?from-embed https://codesandbox.io/p/sandbox/framer-motion-5-drag-to-reorder-lists-with-drag-handle-j9enw?from-embed https://codesandbox.io/p/sandbox/framer-motion-5-drag-to-reorder-lists-uonye?file=%2Fsrc%2Fuse-raised-shadow.ts&from-embed

3. Steps to reproduce

Steps to reproduce the behavior:

  1. Go to the examples update version in package.json to newer version eg "^11.1.8"
  2. See deprecated warning

4. Code replacement

import { animate, MotionValue, useMotionValue } from 'framer-motion';
import { useEffect } from 'react';

const inactiveShadow = '0px 0px 0px rgba(0,0,0,0.8)';
const activeShadow = '5px 5px 10px rgba(0,0,0,0.3)';

export function useRaisedShadow(value: MotionValue<number>) {
    const boxShadow = useMotionValue(inactiveShadow);

    useEffect(() => {
        let isActive = false;

        const unSubMotionChange = value.on('change', (latest) => {
            const wasActive = isActive;
            if (latest !== 0) {
                isActive = true;
                if (isActive !== wasActive) {
                    animate(boxShadow, activeShadow);
                }
            } else {
                isActive = false;
                if (isActive !== wasActive) {
                    animate(boxShadow, inactiveShadow);
                }
            }
        });

        return () => {
            unSubMotionChange();
        };
    }, [value, boxShadow]);

    return boxShadow;
}