Start an animation after page loads on react

Viewed 4080

I am trying to make an element animate after the page loads on react, how do I do that please.

I'm new to react so I don't really know how to target the class and animation, but here is the

HTML and CSS

<div className="dangle" >
</div>
.dangle {
  animation: swing ease-out 5s forwards;
  float: left;
  background-color: red;
}

link to codepen sample

Please I need the solution in react please

2 Answers

First, use "useState" to decide whether to apply animation. ( changing the state of the page )

Second, use "useEffect" to make the desired action run after the page loads. If you pass an empty array as the second parameter, the callback is executed only once after the page is loaded.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <style>
    body {background-color: powderblue; display:grid; place-items: center;}
    @keyframes swing {
      0% { transform: rotate(30deg); }
      100% { transform: rotate(-30deg); }
    }
    .dangle {
      animation: swing ease-out 5s forwards;
      float: left;
      background-color: red;
    }
  </style>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      class App extends React.Component {
        constructor(props) {
          super(props);
          this.state = {animate: false};
        }
        componentDidMount(){
          this.setState({animate: true})
        }
        
        render() {
          return <div className={this.state.animate ? "dangle" : ""}>Hello</div>;
        }
      }

      ReactDOM.render(
        <App />,
        document.getElementById('root')
      );

    </script>
  </body>
</html>

You can add a load event:

window.addEventListener('load', (event) => {
  for (let dangle of document.querySelectorAll(".dangle")) dangle.classList.add("loaded");
});

and enhance the CSS to be executed, make sure the CSS is to be executed only when it's loaded:

.dangle.loaded {
  animation: swing ease-out 5s forwards;
  background-color: red;
  height: 10rem;
  width: 10rem;
}

and let's fix the HTML as well:

<div class="dangle" >
  foo
</div>
Related