Search code examples
cssreactjsfadeinfadeout

React - fade in div, pause and fade out div


In my React app, I am trying to fade a div in, wait a bit, and fade it back out. Everything is working great except the fade out. My SCSS looks like this:

$orange-color: #DD7C15;
$white-color: #FFFFFF;
$black-color: #222222;

.App {
  font-family: sans-serif;
  text-align: center;
}

.message-banner {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 100000;
  width: 100vw;
  color: $orange-color;
  font-size: 4em;
  text-align: center;
  background-color: $white-color;
  border: 2px solid $black-color;
  opacity: 0.9;
  animation: fadeIn 2s ease-in;

  &.hide {
    opacity: 0;
    animation: fadeOut 2s ease-out;
  }
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 0.9;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 0.9;
  }
  100% {
    opacity: 0;
  }
}

And my relevant React code:

const showBanner = () => {
    setMessageBannerText("My sweet awesome banner!!");
    setTimeout(() => {
      setMessageBannerText("");
    }, 3000);
  };

  const bannerClasses =
    messageBannerText === "" ? "message-banner hide" : "message-banner";

I've created a sandbox showing what I am talking about. https://codesandbox.io/s/brave-grass-q1y6j


Solution

  • Hey I have edited your sandbox to achieve the result you desire:-

    Edit vigilant-water-x135f

    Changes:-

    1) Added show and hide classes.

    2) Introduced a boolean state for transition rather than depending on text because your message-banner div doesn't have its own height or width. We will simply let the text stay but hide the div away from the user.

    3) Instead of animation, used transition since you're simply toggling between two states and you want to stick with those for rest of your application. With animation, you will have to do some more tricks for them to stick. Plus animation is useful for more complex scenario.