1

I have a demo. It's a simple React app where I'm displaying an array of text. I'd like to loop through the array and hide and show the text. I thought I might be able to do this in React but I think now it might have to be with CSS. I can hide and show the first color but how can I loop through the colors so it would show Red then Green and etc.

*{
  font-family: Lato;
}

@keyframes fade-animation {
  0% {
    opacity: 0;
  }
  20% {
    opacity: 0;
  }
  40% {
    opacity: 1;
  }
  60% {
    opacity: 1;
  }
  80% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}


.titles{
  position: relative;
  text-align: center;
}

.titles p{
  font-size: 40px;
  position: absolute;
  opacity: 0; 
}

.titles p:nth-child(1) {
  animation: fade-animation 5s linear 0s infinite;
}
/* .titles p:nth-child(2) {
  animation: fade-animation 5s linear 15s infinite;
} */
lomine
  • 873
  • 5
  • 20
  • 36
  • You definitely can't do that in CSS alone. You'd need some advanced logic in React/javascript. Probably adding and removing classes with setInterval. You could have a state variable as a counter to the position in the array. – dmikester1 Feb 06 '20 at 21:52

1 Answers1

0

If for some reason you have to keep the animation logic inside the CSS file, then you'll need the help of Sass/Scss for constructing a loop (see an example here). Pure CSS will not be able to achieve this.

However, a hybrid of React/inline CSS could help. In your React component:

{colors.map((color, i) => (
      <p style={{animation: `fade-animation 30s linear ${i * 5}s infinite`}}>{color}</p>
))}

You might also need to update the animation as follows so that the show/hide happens sequentially. For the above 30s animation with 6 colors, the following animation settings will play correctly.

@keyframes fade-animation {
  0% {
    opacity: 0;
  }
  8.3% {
    opacity: 1;
  }
  16.6% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

To work out the animation math, just make sure the following 2 things:

For n items in the array you wish to loop through:

  1. The percentage of time an item is visible on screen should be 100 / n (in our example above, it is the frames in between 0% - 16.6% where opacity is not 0).

  2. Each item is delayed by m / n where m is the length of the animation (again in our example above, the entire animation takes 30 seconds, so each item is delayed by an additional 5 seconds).

Claire Lin
  • 2,372
  • 8
  • 13
  • Claire LIn - your soultion works but it breaks on the last two colors and I can't work out why - https://stackblitz.com/edit/react-qqrkia?file=index.js – lomine Feb 07 '20 at 10:48
  • @lomine I've updated the code. Please try and let me know if it works. I've also added a bit more explanation on how to work out the animation math. – Claire Lin Feb 07 '20 at 22:25