Search code examples
reactjsmaterial-uicss-transitionslistenerslide

Slide API Mui in React is triggering listener at start not end


I want to have an object slide to the left side of the screen from the right. This is my code:

import rock1 from "src/demos/MyDemo/assets/rock1.png"
import Slide from '@mui/material/Slide';

const Test = () => {

    return (
        <>
            <Slide 
                direction="left" 
                in={true} 
                mountOnEnter unmountOnExit
                timeout={4000}
                easing={{
                    enter: "linear",
                    exit: "linear"
                }}
                addEndListener={()=>alert("Done")}
            >
                <img 
                    height={100}
                    className="Rock" src={rock1}
                    style={{position:"absolute", left: -100, marginBottom:20}}
                />
            </Slide>
        </>
    );
}

export default Test;

I want to do some stuff when the transition ends, so I've added a placeholder end listener for now. However, the listener triggers when the transition starts and does not trigger again when it ends. Why is it happening at the beginning, not the end, and how can I get it to register correctly?


Solution

  • According to the react-transition-group doc that is referenced by MUI on the Slide API page, addEndListener can be used to add another listener for the transition end and pass a callback.

    Live demo for below examples on stackblitz.

    Perhaps try below example for addEndListener:

      addEndListener={(node, done) =>
        // 👇 node is the element being transitioned
        node.addEventListener(
          // 👇 This event fires at the finish of transition
          "transitionend",
          (e) => {
            // 👇 Do something here
            console.log("Actually done");
            done(e);
          },
          false
        )
      }
    

    However, according to the above sources, it seems that another way to achieve the same result here is by adding a callback to the prop onEntered:

      onEntered={() => console.log('onEntered fired')}
    

    Despite the name, onEntered is fired when the transition is complete here, while another prop onExited runs when the exit transition concludes, if applicable. More details can be found in above source links.

    Hope this will help.