javascriptreactjsreact-transition-group

react-transition-group SwitchTransition doesn't work on first update but on all others


I have a react component, basically a card with an image and a title, that is replaced on click with different content. The content is fetched from a WP installation via REST API according to an ID that is updated on click, after the fetch, the content state is updated with the new data, which works just fine. I'm trying to use a SwitchTransition to animate the state change, using a fade-out and fade-in animation.

    <SwitchTransition>
        <CSSTransition key={page} timeout={1000} classNames="fade">
            <CardContent updatePageId={updatePageId} page={page} />
        </CSSTransition>
    </SwitchTransition>

Now, upon page load the CardContent is rendered in the initial state, and that includes firing the "enter-transition" CSS-classes. The Transition ends with the class "fade-enter-done" being applied to the CardContent. However, upon the next CardContent state change (which apparently works as it is supposed to in itself), the SwitchTransition exit and enter classes aren't applied, instead the "fade-enter-done" is never removed.

While I'd usually assume a mistake on my part somewhere, strangely, clicking on another update-trigger will now not only change the CardContent's state but also correctly apply the SwitchTransition. As will all state changes thereafter.

In other words: in this case the SwitchTransition works on initial page load, doesn't work on the first manually triggered state change, but works again on all subsequent manually triggered state changes. What's going on here? What could I be missing?

Thanks for any ideas or solutions!


Solution

  • To answer my own question: I couldn't figure out the reason, but I suppose the problem had to do with the key property of the transition component. I just passed in the entire page (state) object, and apparently, that causes problems. When I used a subset of the object as key (like page.id, or pages[0].id) it started working correctly in all instances.