Home > Blockchain >  How to add CSS animations to a ReactJs component
How to add CSS animations to a ReactJs component

Time:09-27

I'm working on a react component that would render a loading animations.

Here is the js file

import React from 'react'
import './css/CircleSpinner.css'


const CircleSpiner = () => {
    return (
        <div className="lds-circle" >

        </div>
    )
}

export default CircleSpiner

The CSS is on a separate file and the component doesn't render the animations as expected. Any help would be appreciated.

Here's the code sandbox for the above.

CodePudding user response:

You need content or draw the circle:

.lds-circle > div {
  display: inline-block;
  width: 64px;
  height: 64px;
  margin: 8px;
  border-radius: 50%;
  border: 1px solid #000;
  color: black;
  animation: lds-circle 2.4s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}

You are missing border: 1px solid #000; or content so you can view the circle.

Also define the CircleSpiner and use it on your app.js:

CircleSpiner.js

import React from 'react'


const CircleSpiner = () => {
    return (
        <div>
        </div>
    )
}

App.js

export default CircleSpiner

import "./styles.css";
import CircleSpiner from "./CircleSpiner"

export default function App() {
  return (
    <div className="App">
      <div className="lds-circle">
      <CircleSpiner></CircleSpiner>
        </div>
    </div>
  );
}

CodePudding user response:

Your CSS does not correspond to your html. Specifically, this rule here:

.lds-circle > div {
  display: inline-block;
  width: 64px;
  height: 64px;
  margin: 8px;
  border-radius: 50%;
  color: black;
  animation: lds-circle 2.4s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}

The .lds-circle > div selector means "any div which is a direct descendent of .lds-circle". You don't have any descendents of your class so it targets nothing. The second issue is that you are providing a color property which styles foreground elements like text, but you (presumably) want a background-color property to see the background of the div element.

So, putting those two together:

.lds-circle > div {
  display: inline-block;
  width: 64px;
  height: 64px;
  margin: 8px;
  border-radius: 50%;
  background-color: black;
  animation: lds-circle 2.4s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}

@keyframes lds-circle {
  0%,
  100% {
    animation-timing-function: cubic-bezier(0.5, 0, 1, 0.5);
  }
  0% {
    transform: rotateY(0deg);
  }
  50% {
    transform: rotateY(1800deg);
    animation-timing-function: cubic-bezier(0, 0.5, 0.5, 1);
  }
  100% {
    transform: rotateY(3600deg);
  }
}
<div class="lds-circle" >
  <div></div>
</div>

  • Related