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.
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With