Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-spring interpolate function not work with typescript

I decided to introduce TypeScript in my React js application.

Having a problem with a component that uses react-spring for coordinate interpolation.

BEFORE TypeScript my component was like this:


function Card() {
    const [props, set] = useSpring(() => (
        {
            xy: [0, 0],
            config: {mass: 10, tension: 550, friction: 140}
        }));

    const calc = (x, y) => [x - window.innerWidth / 2, y - window.innerHeight / 2]

    return (
        <div onMouseMove={({clientX: x, clientY: y}) => set({xy: calc(x, y)})}>
            <animated.div className="card1" style={{transform: props.xy.interpolate((x,y) => `translate3d(${x / 10}px,${y / 10}px,0)`)}}/>
        </div>
    );
}

everything is working properly.

AFTER typeScript:


function Card() {
    const [props, set] = useSpring(() => (
        {
            xy: [0, 0],
            config: {mass: 10, tension: 550, friction: 140}
        }));

    const calc = (x: number, y: number) => [x - window.innerWidth / 2, y - window.innerHeight / 2]

    return (
        <div onMouseMove={({clientX: x, clientY: y}) => set({xy: calc(x, y)})}>
            <animated.div className="card1" style={{transform: props.xy.interpolate((xy) => `translate3d(${xy[0] / 10}px,${xy[1] / 10}px,0)`)}}/>
        </div>
    );
}

It does not work, I have no compilation errors, simply no translation occurs. The "style" is not injected into the element.

like image 491
Manu Avatar asked Jun 10 '19 16:06

Manu


1 Answers

A little old question but maybe someone could need a better solution. Try to use the interpolate function as Stas Krul mentioned. but you don't have to seperate the properties x and y.

const trans = (x: number, y: number) => `translate3d(${xy[0] / 10}px,${xy[1] / 10}px,0)`

const Card = () => {
const [props, set] = useSpring<{ xy: number[] }>(() => (
    {
        xy: [0, 0],
        config: {mass: 10, tension: 550, friction: 140}
    }));

const calc = (x: number, y: number) => [x - window.innerWidth / 2, y - window.innerHeight / 2]

return (
    <div onMouseMove={({clientX: x, clientY: y}) => set({xy: calc(x, y)})}>
        <animated.div className="card1"
            style={{transform: interpolate(props.xy, trans)}}
        />
    </div>
);

}

like image 195
Max K Avatar answered Sep 30 '22 14:09

Max K