typescriptreact-springreact-use-gesture

How to use react-use-gesture and useSpring in TypeScript?


I am trying to achieve a similar implementation of react-use-gesture and react-spring in TypeScript. The example in JavaScript that I am trying to convert is https://codesandbox.io/s/cards-fduch

I am getting this blank card but when I look at the HTML elements I can see that the cards are being rendered. Why aren't they visible? enter image description here

My attempt in TypeScript is here.

 const to = (i:number) => ({ x: 0, y: i * -4, scale: 1, rot: -10 + Math.random() * 20, delay: i * 100 })
      const from = (i:number) => ({ x: 0, rot: 0, scale: 1.5, y: -1000 })
    const Card:React.FC<Props> = ({ items1}) => {
      const items = [
        'https://upload.wikimedia.org/wikipedia/en/f/f5/RWS_Tarot_08_Strength.jpg',
        'https://upload.wikimedia.org/wikipedia/en/5/53/RWS_Tarot_16_Tower.jpg'
        
      ]
      
     
      const [trans, setTrans] = React.useState( "translateX(0px)");
      
      const [gone] = React.useState(() => new Set()) 
      const [props, set] = useSprings(items.length, (i:number) => ({ ...to(i), from: from(i) })) 
    
      const bind = useDrag(({ args: [index], down, movement: [mx], direction: [xDir], velocity }) => {
          const trigger = velocity > 0.2 
        const dir = xDir < 0 ? -1 : 1 
        if (!down && trigger) gone.add(index) // If button/finger's up and trigger velocity is reached, we flag the card ready to fly out
        set((i) => {
          if (index !== i) return // We're only interested in changing spring-data for the current spring
          const isGone = gone.has(index)
          const x = isGone ? (200 + window.innerWidth) * dir : down ? mx : 0 
          const rot = mx / 100 + (isGone ? dir * 10 * velocity : 0) 
          const scale = down ? 1.1 : 1 
          return { x, rot, scale, delay: undefined, config: { friction: 50, tension: down ? 800 : isGone ? 200 : 500 } }
        })
      });
    
     
      return <>{props.map(({ x, y }, i) => (
        
        <animated.div key={i} style={{ x, y }}>
          {/* This is the card itself, we're binding our gesture to it (and inject its index so we know which is which) */}
          <animated.div {...bind(i)} style={{ backgroundImage: `url(${items[i]})` }} />
        </animated.div>
      ))}</>
      
    
    };  
    export default Card;

Solution

  • This sandbox is using the newer @use-gesture/react and is using typescript.

    Also, the specific image links to wikipedia are not available as of today. That might have also been the reason you didn't see any images rendered