2

I use react-spring with Typescript. When I use the native rendering with react-spring I get an error message to the interpolate function.

"Property 'interpolate' does not exist on type 'number'"

I tried to introduce an interface to the Spring component inner props, but I could not get rid of the various error messages.

import * as React from 'react';
import { FC, useState } from 'react';
import { Spring, animated as a } from 'react-spring/renderprops';

interface Props {
onClick: Function;
}

/*interface SpringProps {
scale: number | Scale;
}

interface Scale {
interpolate: Function;
}*/

const SpringButton: FC<Props> = ({ onClick }) => {
const [pressed, setPressed] = useState(false);
return (
    <Spring native from={{ scale: 1 }} to={{ scale: pressed ? 0.8 : 1 }}>
    {(props /*: SpringProps*/) => (
        <a.button
        style={{
            height: '100px',
            width: '100px',
            transform: props.scale.interpolate(scale => `scale(${scale})`) 
        }}
        onMouseDown={() => setPressed(true)}
        onClick={e => {
            setPressed(false);
            onClick(e);
        }}
        onMouseLeave={() => setPressed(false)}
        >
        Click me
        </a.button>
    )}
    </Spring>
);
};

export default SpringButton;

https://codesandbox.io/s/34zopyr8zq

Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36

1 Answers1

4

The Why

When using the render-props version of react-spring, interpolate is used a little differently than the hooks version. interpolate doesn't exist on scale because scale is just a plain old number, not an object.

The Fix

You will need to import interpolate first:

import { interpolate, Spring, animated as a } from 'react-spring/renderprops';

then style the button using the imported function:

style={{
  height: '100px',
  width: '100px',
  transform: interpolate(
    [props.scale],
    (s) => `scale(${s})`
  ),
}}
Parker Tailor
  • 1,290
  • 13
  • 12
  • It is interesting the typescrpt error gone away in the sandbox. Maybe in the next version it got fixed. Your version is also works without error so it can be also an answer to my question. Since then I switced to the hook api. – Peter Ambruzs May 16 '19 at 07:46
  • How would you write this with multiple interpolate calls? – Tyler Norlund Apr 07 '21 at 15:54