0

I'd like to implement CSSTransition to animate an element but still mount it right away.

Based on the documentation:

By default the child component does not perform the enter transition when it first mounts, regardless of the value of in. If you want this behavior, set both appear and in to true.

So I would think that this example would work:

<CSSTransition
   in={showMessage}
   appear={showMessage}
   timeout={300}
   classNames="alert"
>
.alert-enter,
.alert-appear {
  opacity: 0;
  transform: scale(0.9);
}
.alert-enter-active,
.alert-appear-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;
}

Here is a codesandbox: https://codesandbox.io/s/keen-forest-ghgxq?file=/index.js

As you can see it is displayed right away. I need it to be hidden but still mounted. How do I do this?

Baptiste Arnaud
  • 2,522
  • 3
  • 25
  • 55

1 Answers1

0

But you didn't setup the show property of the Alert component. So by default, it is true

Here's how you can hide it in the beginning, then show and unshow, sandbox

Code:

import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { Container, Button, Alert } from 'react-bootstrap';
import { CSSTransition } from 'react-transition-group';

import './styles.css';

function Example() {
  const [showMessage, setShowMessage] = useState(false);

  useEffect(() => {
    setTimeout(() => {
      setShowMessage(true);
    }, 10000);
  }, []);
  return (
    <Container style={{ paddingTop: '2rem' }}>
      <CSSTransition
        in={showMessage}
        exit={showMessage}
        appear={showMessage}
        timeout={300}
        classNames="alert"
      >
        <Alert
          variant="primary"
          dismissible
          show={showMessage}
          onClose={() => setShowMessage(false)}
        >
          <Alert.Heading>
            Animated alert message
          </Alert.Heading>
          <p>
            This alert message is being transitioned in and
            out of the DOM.
          </p>
          <Button onClick={() => setShowMessage(false)}>
            Close
          </Button>
        </Alert>
      </CSSTransition>
      <button onClick={() => setShowMessage(true)}>
        Show me
      </button>
    </Container>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('root')
);
Robert Tirta
  • 2,593
  • 3
  • 18
  • 37