Initiating change upon componentDidMount

Seeking advice on implementing a transition with react and css. The goal is to apply a class to the span element to achieve the desired animation effect – see illustration below.

Curious to know whether the issue lies in the css implementation or the javascript logic.

class TransitionComponent extends React.Component {
  state = {
    class: null
  };

  componentDidMount() {
    this.setState({
      class: "active"
    });
  }

  render() {
    return (
      <div className="animation-container">
        <span className={this.state.class ? 
                     "animation" : 
                     `${this.state.class} animation`}/>
      </div>
    );
  }
}

const containerElement = document.getElementById("container");
ReactDOM.render(<TransitionComponent />, containerElement);
.animation-container {
  border: 0;
  height: 4px;
  position: relative;
  background: blue;
}

.animation {
  -webkit-transition: width 2s; /* Safari */
  transition: width 5s;
  width: 0%;
}

.animation.active {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Answer №1

Consider trying a different technique by using the active class along with the setTimeout function.

class App extends React.Component {
  state = {
    class: null
  };

  componentDidMount() {
    setTimeout(() => this.refs.progressBar.classList.add("active"), 100)
  }

  render() {
    return ( 
      <div className = "progress-bar-container" >
        <span className="progress-bar" ref="progressBar"/>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render( < App / > , rootElement);
.progress-bar-container {
  border: 0;
  height: 4px;
  position: relative;
  background: red;
}

.progress-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: green;
  transition: width 5s;
  width: 0px;
}

.progress-bar.active {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Answer №2

If you want to trigger a transition on mount, consider using the requestAnimationFrame() method instead of relying on a setTimeout(). This approach is likely more stable and reliable.

componentDidMount() {
    requestAnimationFrame(() => {
        this.setState({
            class: "active"
        });
    });
}

Source:

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

Safari in iOS8 experiencing problems with -webkit-overflow-scrolling: touch;

Our team has been developing a web app for a client that functioned perfectly on iOS7 in Safari. However, upon testing the app on iOS8, some significant bugs were discovered. After a user opens and closes the sidebar, content within a <section style=" ...

Returning to the previous page

Having some trouble navigating back to the previous page. When I click the cancel button, it runs a function that uses history.back();, which works correctly. However, there is a validation on the page, so it checks all fields before navigating back. I&ap ...

What is the process of linking MongoDB with a server?

My attempt to retrieve data from mongoDB while connecting to the server has led me to insert a value into mongoDB in the following manner: > use abc switched to db abc > db.ac.insert({name:"naveen"}) WriteResult({ "nInserted" : 1 }) > show coll ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

Tips for locating and substituting a string in Javascript

Is there a way to locate a particular word within a string and substitute it using JavaScript? For instance Here is a lengthy sentence I want to locate the word "sentence" and modify it to "phrase", resulting in: Here is a lengthy phrase ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

MaterialUI table rows failing to render

I've been facing a challenge with filling a Semantic UI table using an API. Despite my best efforts, I can't seem to get the table to populate with the data from the API. I've tried adjusting the rows to be a variable instead of a state, an ...

What is causing the navigation bar items to shift with the logo when attempting to position it to the left?

Whenever I attempt to shift .logo to the left, it also drags all the other navbar items (Home, Features, Pricing, Disabled) along with it. All I want is for .logo to move to the left without affecting the positioning of the other navbar items. I should me ...

The segmented button's dropdown menu in Bootstrap is malfunctioning on Firefox version 27.0.1

I'm attempting to create a basic search bar using Bootstrap's segmented button feature (check out an example at http://getbootstrap.com/components/#input-groups-buttons-segmented). This is the code I have so far, and it's accessible on jsfi ...

How can I make Div elements disappear based on conditions using If/else Statements in a JSP Page?

I've implemented a JSP function that manages user login by verifying their name and password input. However, even if the user enters incorrect information, they can still view the page. I want to hide all content on the page so that the user cannot se ...

Value of an object passed as a parameter in a function

I am trying to use jQuery to change the color of a link, but I keep getting an error when trying to reference the object. Here is my HTML : <a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav" ...

Can you explain the variance between using @media (max-width: 1000px) and @media and screen (max-width: 1000px) in CSS?

Can someone explain the difference between using @media (max-width: 1000px) and @media and screen (max-width: 1000px) in CSS? When I tested them separately in my code, they seemed to have the same outcome. @media and screen (max-width: 1000px) { .grid ...

The React Material Treeview does not expand tree nodes when clicked if the expanded property is being used

Issue with Treeview not expanding on manual click even when using the expanded property. Unclear why it's failing to expand. <TreeView className={classes.root} defaultCollapseIcon={<MinusSquare />} ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Creating a website account: Including a pop-up notification for successful account creation using ReactJS

Our fan website currently lacks a proper feedback system for user account creation. Once users complete the process, they are redirected to the front page without any indication of whether the creation was successful or not. To determine if their account ...

What is the best way to showcase my Bootstrap navigation menu items below my title in a horizontal layout on mobile devices?

When viewing the website on a desktop, I like how the navigation bar looks. However, when resized to a mobile size, it aligns itself vertically under the heading instead of horizontally, which is what I want. I attempted using "display: inline" but it did ...

modify the name attribute of a select dropdown using jQuery dynamically

In my current project, I am working on dynamically changing the "name" attribute for each select box based on user interactions. The scenario is as follows: When a user clicks on an option in the first select box, a new select box appears with the remainin ...

Encountering TypeScript compilation issues when trying to deploy a Node.js application on Heroku

I've been facing an issue while trying to deploy my TypeScript-based Node server on Heroku. The error I encountered during deployment is as follows: -----> Build Running build > <a href="/cdn-cgi/l/email-protection" clas ...

Express fails to provide a correct response

I have been working on implementing MongoDB to gather data for our analytics page. However, despite seeing the data in the terminal through console log, when I make a request, Express returns an empty array as the response. Here is my endpoint: import Ana ...

Is there a way to showcase the uploaded file contents on the current page without the need to refresh?

Is there a way to display the contents of an uploaded file on the same HTML page without opening a new tab or refreshing it? I have the following HTML and PHP codes for reading an uploaded file in a separate page, but I want to integrate it into the same H ...