Search code examples
javascriptreactjsanimationreact-spring

Is it possible to apply Spring-animation on img src change using React?


In my react application, I am trying to use react-spring to fade in an image when the src changes. I have multiple images in the /img/ directory named to match the current activeIndex I want to display. Currently using below code, the fade in effect is only applied on the first image. What am I doing wrong?

import React from 'react';
import { Spring } from 'react-spring/renderprops';

export default function MyComponent(props) {

    const {
        activeIndex
    } = props;

    return (
        <div>
            <Image activeIndex={activeIndex}  />
        </div>
    )
}

function Image(props) {

    const {
        activeIndex
    } = props;

    return (
        <Spring
            from={{opacity: 0}}
            to={{opacity: 1}}
        >
            { props => (
                <div style={props}>
                    <div>
                        <img src={ `/img/${activeIndex}/01.jpg` } alt="" />
                    </div>
                </div>
            )}
        </Spring>
    )
}

Solution

  • If you just want the fade in effect, make sure that every Image has different key. In this case react will repeat the initial effect.

    return (
        <div>
            <Image key={activeIndex} activeIndex={activeIndex}  />
        </div>
    )
    

    If you want a fade out effect as well. I would try the Transition component instead of the Spring component.