Search code examples
reactjsreact-spring

upgrade react-spring code that uses animate and transition to latest react-spring


I have this code that uses react-spring 4.0.1 code:

export const Nodes: React.FunctionComponent<NodesProps> = ({nodes, nodeClickHandler}) => {
  return (
    <Transition
      native={true}
      items={nodes}
      keys={keyAccessor}
      config={{ tension: 1000, friction: 130, mass: 5 }}
      from={(node: HierarchyPointNode<GraphicalNode>) => {
        const parentTopLeft = !!node.parent
                              ? {left: node.parent.x, top: node.parent.y}
                              : {left: 0, top: 0};
        return {
          left: parentTopLeft.left,
          opacity: 0,
          top: parentTopLeft.top,
        };
      }}
      enter={(node: HierarchyPointNode<GraphicalNode>) => {
        return {
          left: node.x,
          opacity: 1,
          top: node.y,
        };
      }}
      update={(node: HierarchyPointNode<GraphicalNode>) => {
        return {
          left: node.x,
          opacity: 1,
          top: node.y,
        };
      }}
      leave={(node: HierarchyPointNode<GraphicalNode>) => {
          return {
            left: node.x,
            opacity: 0,
            top: node.y,
          };
      }}
    >
    {nodes.map((node: HierarchyPointNode<GraphicalNode>) => (styles: CSSProperties) => {
        const key = keyAccessor(node);
        return (
          <animated.g
            className="cx-group"
            style={{
              cursor: "pointer",
              pointerEvents: (styles.opacity as any).interpolate((v: any) => v < 0.5 ? "none" : "all") }
            }
            width={40}
            height={20}
            opacity={styles.opacity}
            transform={template`translate(${styles.left}, ${styles.top})`}
            key={keyAccessor(node)}
          >
            <Node node={node} nodeClickHandler={nodeClickHandler} key={key} />
          </animated.g>
        );
      })}
    </Transition>
  );
};

In react-spring 8, there is no transition and animate.

How can I upgrade this code to the latest version.


Solution

  • In version 8 the renderProps api can be accessed from react-spring/renderprops. So you can try with the following import.

    import {Transition, animated} from 'react-spring/renderprops';
    

    You can also try the hooks api. I think the code is more simple, I love it.