1

I am new to React. I want my rectangle to fade in and out when the button is clicked. I use for this. I do everything according to the documentation. Here is my component code:

import React, {useRef, useState} from 'react';
import {CSSTransition} from "react-transition-group";

const Test = () => {
    const [visible, setVisible] = useState(false)
    const nodeRef = useRef(null);

    return (
        <div>
            <button onClick={() => setVisible(!visible)}>ACTION</button>
            <CSSTransition
                in={visible}
                nodeRef={nodeRef}
                timeout={500}
                classNames="alert"
                mountOnEnter
                unmountOnExit
            >
                <div className="square"/>
            </CSSTransition>
        </div>
    );
};

export default Test;

And my css code:

.square {
    background-color: red;
    height: 200px;
    width: 200px;
}

.alert-enter {
    opacity: 0;
    transform: scale(0.9);
}
.alert-enter-active {
    opacity: 1;
    transform: translateX(0);
    transition: opacity 300ms, transform 300ms;
}
.alert-exit {
    opacity: 1;
}
.alert-exit-active {
    opacity: 0;
    transform: scale(0.9);
    transition: opacity 300ms, transform 300ms;
}

From what I see on the screen a red square, I conclude that my component sees the css file. I also understand that the wrapper works because the square disappears and appears when the button is pressed. But the animation doesn't work and I don't know why. The css code that describes the animation is taken from the official documentation. What am I doing wrong?

1 Answers1

0

You just need to remove nodeRef={nodeRef} from your CSSTransition. So your code should be:

<div>
  <button onClick={() => setVisible(!visible)}>ACTION</button>
  <CSSTransition
   in={visible}
   timeout={500}
   classNames="alert"
   mountOnEnter
   unmountOnExit
  >
    <div className="square"/>
  </CSSTransition>
</div>
Learning
  • 1,333
  • 16
  • 24