2

I'm fairly new to React and react-transition-group. I'm making a very simple app that displays a word of the day, and I'm having some trouble with animating my info cards.

It essentially works like an image carousel. If the user clicks a left arrow, the current content slides off to the right and new content slides in from the left. If the user clicks a right arrow, the current content slides off to the left and new content slides in from the right.

The problem is, with react-transition-group you have to set your CSS class names when the component renders. But I don't know which direction the component needs to exit until after it's already been rendered. This means sometimes the components exit the wrong way.

import React from "react";
import words from  '../words.json';
import { TransitionGroup, CSSTransition } from 'react-transition-group';

class TodaysDefinition extends React.Component{

    render(){
        let {day, nextOrPrev} = this.props;
        let {def} = words[day - 1 ];

        //trying to set the classNames prop based on which button was pressed last.
        let transitionClass = "";
        if(nextOrPrev === -1){
            transitionClass = "prev-defs";
        }
        else{transitionClass = "next-defs";}

        return(
            <div className="def-container">
                <TransitionGroup component={null}>
                    <CSSTransition
                    classNames={transitionClass}
                    key={this.props.day}
                    timeout={{enter:300, exit:300}} >
                        <ol className="defs">
                            {def.map((def,idx) => (<li key={idx} >{def}</li>))}
                        </ol>
                    </CSSTransition>
                </TransitionGroup>
            </div>
        )
    }
}

export default TodaysDefinition;

Thanks for your help!

georgedum
  • 491
  • 3
  • 10

1 Answers1

1

As far as I can tell, there's no built-in way to do this via react-transition-group except with their callback functions.

<CSSTransition
                classNames="next-defs"
                key={this.props.day}
                timeout={{enter:300, exit:300}}
                onEnter={(node) => this.enter(node)}
                onEntering={(node) => this.entering(node)}
                onExit={(node) => this.exit(node)}
                onExiting={(node) => this.exiting(node)} >
                    <ol className="defs">
                        {def.map((def,idx) => (<li key={idx} >{def}</li>))}
                    </ol>
                </CSSTransition>

I have four functions that I use to add classes to the appropriate node at the same times react-transition-group normally does it automatically. I keep track of what button was pushed last in state, and then add the appropriate class.

I'm not super happy with the solution, but it works for this project. I'm very curious if there's a more react-like way to do this.

georgedum
  • 491
  • 3
  • 10