React: Animate with CSS

How can I make sure that every time a new user is prepended, the first div has a CSS animation? Currently, my code only works for the first prepend and the animation does not trigger on subsequent ones.

const [userList, setUserList] = useState<any>([]);
<div className='user-listing absolute top-0 left-0'>
    {
        userList.map((user:any, index:number)=>{
        return (
            <div key={index} className='user'>{user}</div>
        )
        })
    }
</div>
<button onClick={()=> setUserList((list:any) => [randomUser(),...list])}>
  add
</button>
.user-listing{
  .user{
    &:first-child {
      animation-name: fadeIn;
      animation-duration: .15s;
    }
  }
}

@keyframes fadeIn {
  0% {
      opacity: 0;
      transform: scale(.2)
  }

  to {
      opacity: 1;
      transform: scale(1)
  }
}

Answer №1

What's going on is that the key prop remains constant in the initial element of the list, causing React to update the elements with existing keys and add a new one at the end of the list with a new key.

Initially, there is an element with the key 0, which is new, triggering the animation. Then, when you append a new element to the user list, the element with key 0 stays at the top of the list in the DOM, so it isn't considered a new element but rather updated with the new user's name. The truly new element will have the key 1 (using data from the existing user) and so forth.

This is why using array indexes as keys is not recommended.

To ensure the animation plays for each new element added to the beginning of the array, use a unique key that identifies the user (such as its id or name). In your case, since the user appears to be only a string, you could simply use it like this:

userList.map((user: any) => {
  return (
    <div key={user} className='user'>{user}</div>
  )
})

I hope this clarifies things :)

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

What is the best way to incorporate an icon into my HTML search bar?

I'm having trouble getting the search icon from font awesome to display properly within my search bar. Here is the code I'm using: <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" rel="stylesheet"/> ...

Having trouble accessing certain pages in a React .NET application without a direct link?

I developed a React application with .NET using Visual Studio, and everything runs smoothly when tested locally. After deploying the app to Azure App Service, the home page functions properly. However, I encounter a 404 Not Found error when attempting to a ...

"ENUM value is stored in the event target value's handle property

My issue lies with the event.target.value that returns a 'String' value, and I want it to be recognized as an ENUM type. Here is my current code: export enum Permissions { OnlyMe, Everyone, SelectedPerson } ... <FormControl> & ...

Reports of missing packages in the React Starter Kit have caused confusion among users

While I may be new to React/JS, I have a wide range of experience in different technologies, including some work with Angular/JS. Therefore, my encounter with the Node/JS ecosystem is not completely fresh. The journey began when I encountered a missing pe ...

When utilizing date-fns and comparing dates with isWithinInterval in a specified timezone, an error occurs indicating an invalid interval

For my upcoming project, I am retrieving UTC time from an API. To ensure accuracy, I need to convert the UTC times to the local time of the user based on their timezone setting obtained from the API. I attempted to utilize the isWithinInterval function fr ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

The mp4 video on the website will only load if the Chrome developer tools are activated

Whenever I try to play the video set as the background of the div, it only starts playing if I refresh the page with Chrome dev tools open. HTML: <div id="videoDiv"> <div id="videoBlock"> <img src="" id="vidSub"> <video preload="prel ...

You can only import Next.js Global CSS from your Custom <App> and not from any other files

Initially, my React App functioned perfectly with global CSS included. However, after running npm i next-images, adding an image, modifying the next.config.js file, and executing npm run dev, I encountered the following notification: "Global CSS cannot ...

Is the 'previousState' variable in React able to be changed?

After searching for an answer to this question for quite some time, I have decided to just ask it: When passing a function as the first parameter to this.setState, is previousState mutable? https://i.stack.imgur.com/vcnyv.png The documentation mentions ...

Is there a way to edit a cell in the MUI X Data Grid without having to double-click

Is there a way to change the MUI XData Grid cell editing behavior so that it always displays in edit mode or by hovering, rather than requiring a double click? ...

The order of CSS precedence shifts even when the class sequence is the same

In my development setup, I have a react component that is embedded within two distinct applications each with their own webpack configurations. Within the component, I am utilizing a FontAwesome icon using the react-fontawesome library: <FontAwesom ...

Utilize the ::before selector to insert white spaces

I attempted this solution, but unfortunately it did not produce the desired outcome: .stackoverflow::before { font-family: 'FontAwesome'; content: "\f16c "; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-aw ...

create a gentle appearance for an element

I am looking to replicate the visual appearance of each page on this particular website: There is something about the lighting that I really admire. I have attempted to recreate the animation, but I have been unsuccessful in my attempts. Any assistance wo ...

How can I improve the smoothness of my CSS transition when resizing background images?

I'm currently working on creating an intro movie for a game and I thought it would be interesting to use CSS animations. However, I've noticed that some parts of the animation appear bumpy and inconsistent. It seems that depending on the transiti ...

Having trouble getting the toggle menu to work using Jquery?

I am trying to create a toggle menu using jQuery on this particular page: . The menu is located in the top right corner and I want it to appear when someone clicks on the "Menu ☰" button, and then disappear when clicked again (similar to this website: ). ...

Adjust the left margin to be flexible while keeping the right margin fixed at 0 to resolve the spacing

To create a responsive design that adjusts based on screen size, I initially set the content width to 500px with a margin of 0 auto. This meant that for a 700px screen, the content would remain at 500px with left and right margins of 100px each. Similarl ...

Email in HTML format: content rendering poorly in Outlook

Below is the code I am using to display text with an image. <table width="220" align="right" style=""> <tr> <td> <table align="left" width="100" style="padding: 0; Margin: 0; Margin-top:15px;"> <tr& ...

modifying Redux state according to the position in an array

In my food truck app, I have stored customer orders in the redux state as an array of objects. Each order includes a list of items selected by the customer, along with the count, name, and total price for each item. For example: state.order = [ {item: " ...

Is there a way to alter the behavior of a MUI v5 Button to lighten on hover instead of darken using the theme settings

I followed the instructions in the documentation to set up my theme. palette: { primary: { main: customColor } } After setting up, I noticed that when I hover over my mui button, it darkens based on the main color. However, I want it to li ...

Optimize React Material UI: Stop unnecessary re-rendering of child component Tabs when switching tabs

I have multiple "tasks" with individual sets of tabs that I want to organize. Each tab within the TabPanel contains a TaskOrg component responsible for fetching data from the backend through API calls and displaying it in a DataGrid. The issue arises when ...