Skip to content Skip to sidebar Skip to footer

Apply Css Animation To Div When Array.map Added Or Remove Div In React.js

For reference, check out this StackBlitz Link I have css animation @keyframes class.. /* Animation classes. */ .example-enter { animation: flasher 0.5s; } @keyframes fla

Solution 1:

I guess the problem is on this line, you're using index as key for your LineItem.

todoState.map((item, index) =><LineItemkey={index}todoList={item}index={index}/>)

React does not recomment using indexes for keys, read more here.


You need to have some sort of id to uniquely identify your todo items and use that id as key when you do your todoState.map((item) => .... So you'll have to make your todo item as an object and not a string.

In your TodoForm, we'll add a generateId and use this functions return value for our new todo's id.

TodoForm.tsx

functiongenerateId() {
  // https://stackoverflow.com/a/8084248/8062659returnMath.random().toString(36).substring(7);
}
constsendTodoItem = (e) => {
  if(todoInput.trim().length > 0){
    const text = todoInput.trim();
    const id = generateId();

    addNewTodoState({ text , id }); // notice heresetIsDisabled(false);
    setTodoInput('');
  }else{
    setIsDisabled(true);
  }
}

Now on you TodoListLineItem, we'll remove the index from map and use the current todo's id as key.

TodoListLineItem.tsx

todoState.map((item) =><LineItemkey={item.id}todoList={item}/>)

We also have to update your Line-Item to display the text property of the current todo.

Line-Item.tsx

<p>{todoList.text}</p>

Check this link for a demo.

--

Because we're using now an object as a todo item, I believe you should also make changes on some parts of the app, like the model and the delete feature. But the changes above should be sufficient to achieve what you want as described on your post.

Solution 2:

A simple approach is to add the animation class with useEffect and remove it after the duration of the animation.

importReact, {useEffect, useState} from'react'constYourApp = props => {
 
  const [animate, setAnimate] = useState(false)
  const [todoState, setTodoState] = useState([])

  useEffect(() => {
    setAnimate( true )
    setTimeout( () => { setAnimate( false ) }, 500 )
  }, [todoState])


  return<divclassName={animate ? "example-enter" :null } > ... </div>
}

Each time you update todoState, it will apply the animation class for 0.5s basically.

Post a Comment for "Apply Css Animation To Div When Array.map Added Or Remove Div In React.js"