Creating a grid with individual node delays in CSS animations using ReactJS

Struggling with a CSS animation issue in ReactJs. I suspect the problem, but unsure how to solve it.

I'm rendering a 5x5 grid and displaying it using this function:

  DisplayNodes = () => {
    const {grid} = this.state; // get the node array from state
    return (
      <div id="grid">
        {grid.map((rowMap, rIndex) => {
          return (
            <div class="row">
              {rowMap.map((node,nIndex) => {
                return (
                  <Node/>
                );
              })}
            </div>
          )
        })}
      </div>
    )
  }

This creates a 5x5 grid. Each Node object has a className of node, with some nodes having unique classes and styles.

.node {
  width:20px;
  height:20px;
  border:1px solid gray;
  cursor: pointer;
  user-select: none;
  background-color: black;
  transition: background-color 500ms linear;
}

The intended effect was for each node to transition to a black background color over 500ms one after another, creating a fade-in effect. However, all nodes change color simultaneously after 500ms.

I suspect this is due to the pre-calculation during mapping resulting in synchronous rendering. I've tried using a setTimeout function within the map, but this caused nodes to be drawn in incorrect grid locations.

Answer №1

There is an alternative approach to achieve this task.

Instead of sequentially delaying each node, you can calculate the delay time from the initial moment.

For instance, if each node needs 500ms to change color and the next node starts after 500ms, the delay for the first node would be 0ms, for the second node it would be 500*1 ms, for the third node it would be 500*2 ms, and so on.

Therefore, the mapping function should pass the index of each node as a prop:

 DisplayNodes = () => {
    const {grid} = this.state; // retrieve the node array from state
    return (
      <div id="grid">
        {grid.map((rowMap, rIndex) => {
          return (
            <div class="row">
              {rowMap.map((node,nIndex) => {
                return (
                  <Node index={nIndex}/>
                );
              })}
            </div>
          )
        })}
      </div>
    )
  }

In the node render function, set the correct transition-delay CSS based on the node index:

Node =(index)=>{
  const delay = index*500 + "ms";
  return <div style={{transitionDelay:delay }}>...<div>;
}

By following this approach, the nodes will animate one by one smoothly.

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

Halt spread: descend in a bubble?

It seems that the issue at hand may not be related to propagation, but rather a design flaw. I have come across information suggesting that propagation problems tend to bubble up, however, let me explain my situation. I am working with a table edit grid. ...

The reference to NativeModules.MyNativeModule is not found in iOS when using react native version 0.61.2

I'm currently working on a React Native library that is stored locally. To install it, I use the command yarn add ../MyNativeModule When importing it into my code, I usually do const MyNativeModule = NativeModules.MyNativeModule;. This setup works ...

The Vue component should trigger the display of data in a Bootstrap modal based on the row of the button that was

Here is a sample code snippet demonstrating how data is fetched from the database: <table class="table table-bordered"> <thead> <tr><th>User ID</th><th>Account Number</th><th>Accou ...

Is the fs.watch method being triggered unexpectedly?

As a beginner in node.js and javascript, I've been experiencing an error with the following code snippet: fs.watch('F:/junk', (eventType, filename) => { if(filename && filename.split('.')[1].match("zip")) { ...

What sets apart the various useEffect functions in React?

useEffect(() => { return () => setTimeout(() => set_current_focus(index_map[comp_index]), 1000); }, [comp_index]); In addition, useEffect(() => { return setTimeout(() => set_current_focus(index_map[comp_index]), 1000); } ...

Guide on invoking setImmediate prior to or above .on('data') in fast-csv using Node.js

I'm currently utilizing fast-csv (https://www.npmjs.com/package/fast-csv) for parsing a csv file. The file could possibly contain 10k records, leading to significant delays in parsing and blocking other operations on the server. To address this issu ...

There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { i ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

The combination of Material UI and React Hook Form is encountering an issue with submitting disabled checkboxes

My current challenge involves ensuring that all fields are disabled while the form is submitting. I have successfully implemented this for text, selects, and radios, but I am facing difficulties with required checkboxes. I am working with nextjs typescrip ...

Windows npm configuration settings

After receiving helpful answers to my previous question about using a named parameter in an npm run script, I encountered a new problem. It seems that the $npm_config_variable doesn't function correctly on Windows OS. I am in search of a solution that ...

Tips for hiding website content on larger screens

Is there a way to hide website content on screen sizes over 1600px and display only a message image instead? ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

Can you explain the significance of argument[0] in JavascriptExecutor?

I recently implemented the "How to handle hidden web elements using the JavaScript executor method". However, I am still unclear about how the method works. public static void selectDateByJS(WebDriver driver, WebElement element, String dateVal) { Javas ...

Set up a Bootstrap date picker to populate two input boxes with a start and end date. Additionally, disable the ability for the date value to change

In my project, I have implemented Bootstrap Datepicker to set two input boxes for selecting start and end dates. The rule is that the start date must be after today and the end date must be after the selected start date. To disable specific dates in the da ...

When the Select component in Formik-Material-UI is clicked, the app bar color changes dynamically

I'm currently working on a web project that utilizes React, Material, Formik, and formik-material-ui. One of the components I have included is a select component, shown below import { Formik, Form, Field } from "formik"; import { TextField ...

Changing the style of Vuetify v-list-item when hovering over it

I just started using Vuetify and I came across a v-list sample that I need help with. Here is the link to the Vuetify v-list sample on Github. My v-list: https://i.sstatic.net/ykTIi.jpg Code: <template> <v-card max-width="500" class= ...

Angular Logout does not reset local storage items

My ng-click logout function in the view: <div class="navbar navbar-default"><div class="container"> <div id="navbar-main"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> <li ng-show=" ...

Do you think the linter might be mistakenly flagging unique keys as false positives?

function displayRows(products) { return products.map(({ name, price, category, stocked }, index, currArr) => // Is the category of the previous item in the array the same as the current item's category? currArr[index - 1]?.category === cu ...

Switching between dark and light mode in Ant Design

I have successfully implemented dark mode toggling in my application. However, when I try to switch back to light mode, the CSS does not seem to be reloading properly. Below is the code snippet: //ThemeContext.jsx const DarkTheme = lazy(() => import(". ...