The animated element in React is not running despite the animation class being added through addEventListener

When I add an animation class triggered by a scroll event listener, the progress bar animation only runs once on page load and does not run again when I scroll. Is there an issue with the code or is setState being used incorrectly?

.body2 {
  background-color: #151515;
  height: 700px;
}

.title2 {
  font-size: 40px;
  font-family: handwritten;
  color: #d10100;
  text-align: center;
  padding-top: 100px;
  grid-area: 1 / 1 / 2 / 2;
  letter-spacing: 5px;
  font-stretch: extra-condensed;
}

.titleback2 {
  font-size: 90px;
  font-family: ARCHIVO-bold;
  -webkit-text-stroke-color: #212121;
  -webkit-text-stroke-width: 3px;
  color: #151515;
  text-align: center;
  padding-top: 75px;
  grid-area: 1 / 1 / 2 / 2;
}

.bar{
  background-color: #e3e3e3;
  width: 400px;
  height: 20px;

}

.bargrid {
  margin: 200px;
  height: 500px;
  display: grid;
  grid-template: 1fr 1fr  1fr/ 1fr 1fr;
  justify-items: center;
}

.barlabel {
  color: #e3e3e3;
  font-family: cafe;
  padding-bottom: 10px;
}

.progress{
  background-color: #d10100;
  background-image: linear-gradient(to right, #d10100 30%,#ff3231, #ff5f5e);
  height: 20px;
  position: relative;
  bottom: 20px;
  padding-left: 2px;
  padding-right: 2px;
  
}

.loadpage {
  animation: progressbar 2s normal;
}

@keyframes progressbar{
  0% {width: 0%}
  100% {width: 100%}

}

import React from "react";
import './Skills.css';

class Skills extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            progress: 'progress',
        }
        this.changeState = this.changeState.bind(this)
    }

    changeState = () => {
        this.setState({
            progress: 'progress loadpage'
        })
    }

    componentDidMount(){
        window.addEventListener('scroll', this.changeState)
        this.setState({
            progress: 'progress'
        })
    }

    render() { 

        return (
        <div className="body2">
            <div className="container">
                <div className="titleback2">SKILLS</div>
                <div className="title2">skills</div>
            </div>
            <div className="bargrid">
                <div className="cell1">
                    <div className="barlabel">HTML</div>
                    <div className="bar" />
                    <div className={this.state.progress} />
                </div>
                <div className="cell2">
                    <div className="barlabel">CSS</div>
                    <div className="bar" />
                    <div className={this.state.progress} />
                </div>
                <div className="cell3">
                <div className="barlabel">JAVASCRIPT</div>
                    <div className="bar" />
                    <div className={this.state.progress} />
                </div>
                <div className="cell4">
                    <div className="barlabel">REACT.JS</div>
                    <div className="bar" />
                    <div className={this.state.progress} />
                </div>
                <div className="cell5">
                    <div className="barlabel">FRAMER MOTION</div>
                    <div className="bar" />
                    <div className={this.state.progress} />
                </div>
                <div className="cell6">
                    <div className="barlabel">HTML</div>
                    <div className="bar" />
                    <div className={this.state.progress} />
                </div>
            </div>
        </div>
        );
    }
}

export default Skills;

Answer №1

To simplify this, you can utilize the animationend event in JavaScript.
For more information, refer to the MDN documentation link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event

Here is a helpful resource on CodeSandbox that demonstrates this concept:
Code sandbox address. ( https://codesandbox.io/s/react-playground-forked-yzmjrn?file=/index.js )

Skills.js

import React from "react";
import "./Skills.css";

class Skills extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      progress: "progress"
    };
    this.changeState = this.changeState.bind(this);
  }

  changeState = () => {
    this.setState({
      progress: "progress loadpage"
    });
  };

  componentDidMount() {
    window.addEventListener("scroll", () => {
      console.log("scrolling...");
      this.changeState();
    });
    this.setState({
      progress: "progress"
    });

    document.addEventListener("animationend", (e) => {
      console.log("Animation ended");
      if (e.animationName === "progressbar") {
        this.setState({
          progress: "progress"
        });
      }
    });
  }

  render() {
    return (
      <div className="body2">
        <div className="container">
          <div className="titleback2">SKILLS</div>
          <div className="title2">skills</div>
        </div>
        <div className="bargrid">
          <div className="cell1">
            <div className="barlabel">HTML</div>
            <div className="bar" />
            <div className={this.state.progress} />
          </div>
          <div className="cell2">
            <div className="barlabel">CSS</div>
            <div className="bar" />
            <div className={this.state.progress} />
          </div>
          <div className="cell3">
            <div className="barlabel">JAVASCRIPT</div>
            <div className="bar" />
            <div className={this.state.progress} />
          </div>
          <div className="cell6">
            <div className="barlabel">HTML</div>
            <div className="bar" />
            <div className={this.state.progress} />
          </div>
        </div>
      </div>
    );
  }
}

export default Skills;

This implementation may not be flawless, but I hope it provides some assistance! 😊

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement isotope filter on product page details using ASP.NET Core MVC

While working on my .Net core project, I implemented an isotope filter dynamically. Everything seemed to be functioning correctly, however, a minor error occurred. When selecting a specific category, the position of the product did not appear as expected. ...

Leveraging body parameters within an ExpressJS post Route

Currently, I am utilizing ExpressJS and MongoDB with a NodeJS Runtime backend, but I am facing a challenge in sending previously filled out form data to the next page for further steps in the form. The form consists of multiple pages. For instance, when cr ...

How can I incorporate a child component into a separate component within Angular version 14?

Currently working with Angular 14 and facing a challenge with including a child component from another module into a standalone component. The structure of the standalone component is as follows: <div> <child-component></child-component& ...

How can I retrieve a value calculated using props within the componentDidMount lifecycle method?

I am currently in the process of converting a vanilla JavaScript GSAP (GreenSock) animation into React. I need to access values based on props in componentDidMount where GSAP tweens are called. The animation is inspired by this CodePen demonstration: https ...

Unable to retrieve array values from an object

Having trouble retrieving values from an array in an object. Looking for some assistance. Below is the JSON parsing code: let userContent = null; try { userContent = JSON.parse(entity.contactform_content); } catch (e) { userContent = String( ...

Challenges encountered when implementing a personal library in a separate project

After updating a library I own, I seem to have encountered an issue when trying to use it in another project. However, the reason for this problem eludes me. A multitude of error logs with a similar theme are appearing: ERROR in ./node_modules/@company-na ...

What is the best location to store a Variable in React in order to access it throughout my entire application?

Hey everyone, I'm currently working on some updates for a React app as a beginner. I have a query regarding a const named Users List which looks like this: "u_469": { "ID": "469", "UID": " ...

What is the reason for the neglect of this function's definition?

Is there a reason behind the error message I am receiving? TypeError: getStatusCode(...) is not a function This error occurs when I execute the following code: const getStatusCode = require('./getStatusCode') tmpStatus = await getStatusCode({url ...

Ways to extract text content excluding HTML elements

Managing a database table for news storage has been pretty straightforward, as the field type is TEXT which allows me to save the news with inline styles. However, I encountered an issue when trying to display the last 10 news items on the main page. While ...

Finding and identifying specific text within Paper Material-UI can be achieved through a few

I have been attempting to vertically center the text inside a Paper component from material-ui. Below is my code: const style = { height: 150, width: 150, margin: 20, textAlign: 'center', rounded: true }; render () { ...

only a single backdrop filter can be in use at any given moment

Experimenting with backdrop-filter in Chrome 76. I'm working on a menu with 2 divs, each with a backdrop-filter applied. The first div is displaying the filter effect perfectly, but the second one isn't. Interestingly, when I remove the filter fr ...

How can PHP be used to access every element within an array that has been passed through an AJAX call?

I am having trouble accessing elements within an array from my PHP file after passing the array through an ajax call. Here is the code for the ajax call: var data = ['test1', 'test2', 'test3']; $(document).ready(function () { ...

Repetitive firing of events implemented using AngularJS

Hello, I'm currently trying to trigger an event repeatedly in AngularJS. Below is the code snippet: Here is the HTML code: <li ng-repeat="y in names | limitTo: 6" repeat-done="ratingwithng()"> <a href="<?php echo $this->config-> ...

Issue with ellipsis not functioning correctly on dynamic placeholders when they are in focus

When I focus on my dynamic placeholder input, the text-overflow: ellipsis property is lost for some reason. However, it is regained when blurred. Can anyone explain why this is happening? If you want to experiment with it, I have set up a stackblitz: htt ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

Experiencing issues with ng-repeat in AngularJs?

I am currently facing an issue with two tables that are rendering data through AngularJS from two separate C# methods. Both tables have almost identical structures, with the first one being used as a search field and the second one to display names. The pr ...

A guide to retrieving all keys from a JSON object in Javascript

{"data": {"characters":[ {"name":["Harry Potter"],"age":["18"],"gender":["Male"]}, {"name":["Hermione Granger"],"age":["18"],"gender":["Female"]} ]} } In the given JSON data, I am interested in retrieving the keys like name, age, gender for ea ...

What could be causing the issue with the <bgsound src="music/binks.mp3"/> not functioning properly?

Looking to add some background music to my website, but struggling to find current information after searching for 15 minutes. Can anyone provide assistance? <body> <bgsound src="music/binks.mp3"/> </body> <bgsound src=& ...

Hover state not responsive on screens of varying sizes due to style inconsistencies

Here are the CSS styles I'm using: @media (min-width: 769px) and (max-width: 992px) { .box:hover{ background-color:#000000; } } @media screen and (min-width: 993px) { .box:hover{ background-color:#ffffff; ...

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicked on?

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicking anywhere on the page? <table id="view_table" data-toggle="table" data-search="true" data-page-list="[5, 10, 20]" data- ...