Natesh bhat
Natesh bhat

Reputation: 13202

component snapping effect when animation transitions out in react-spring?

I am trying to have an animation every time the picture component gets changed. The first animation when the page loads , is fine. When I click the '+' button , the animation kind of snaps back to its final position in a jerk and is not smooth. I don't understand why this snap effect is happening. How do i fix this ?

const PictureArt = (props) => {
    const imageStyle = {
        width: '100%',
        height: 'auto',
        borderRadius: '5px',
        boxShadow: '5px 5px 20px',
    }


    const [items, setItems] = useState([{
    url: 'http://4.bp.blogspot.com/-mZwB8lpO3-0/UN1r7ZrbjnI/AAAAAAAADBU/rqa5a2DD_KY/s1600/White_Flower_Closeup.jpg',
    caption: 'flower',
    description: "When the flower looked beautiful ... "
}, {
    url: 'http://4.bp.blogspot.com/-mZwB8lpO3-0/UN1r7ZrbjnI/AAAAAAAADBU/rqa5a2DD_KY/s1600/White_Flower_Closeup.jpg',
    caption: 'flower',
    description: "When the flower looked beautiful ... "
}]);

    const [currentIndex, setCurrentIndex] = useState(0);

    const totalItems = items.length ; 

    const picTransition = useTransition(currentIndex , null, {
        from: { opacity: '0', transform: `translate3d(100px,0px,0)` },
        enter: { opacity: '1', transform: 'translate3d(0,0,0)' },
        leave: { opacity: '0', transform: `translate3d(-100px , 0px , 0)` },
    })
    const currentItem = items[currentIndex] ; 

    return (
        <>
            <button onClick={e=>setCurrentIndex((currentIndex+1)%totalItems)}>"+"</button>
            <div>
                <div className="container">
                    {
                        picTransition.map(({ item, props, key }) => {
                            return (
                                <animated.div style={props} key={key}>
                                    <div style={{ width: '500px' }}>
                                        <img src={currentItem.url} style={imageStyle}  ></img>
                                    </div>
                                </animated.div>)
                        })
                    }

                </div>
            </div>
        </>
    );
}

function App() {
  return (
    <div className="App">
      <h1>Click below + button</h1>
      <PictureArt/>
    </div>
  );
}

Here's a codesandbox snippet : https://codesandbox.io/s/wn6jp23vxl

Upvotes: 0

Views: 1872

Answers (1)

Ga&#235;l S
Ga&#235;l S

Reputation: 1569

I was facing the same issue and I fixed your sandbox by adding a position: absolute to the div wrapping the img. I did that after analyzing that sandbox from the creator of react-spring:

<div style={{ width: "500px", position: "absolute" }}>
  <img src={currentItem.url} style={imageStyle} />
</div>

Hope it helps

Upvotes: 2

Related Questions