0

I have an array of 2 elements with position absolute, those are layouted via top CSS property. Also, there's a CSS transition hooked to the top key. When I exchange elements positions, some elements (although the key doesn't change), the html element is recreated, hence CSS transition doesn't happen.

import { useEffect, useState } from "react";
import "./styles.css";

const Square = ({ backgroundColor, index }) => {
  return (
    <div className="square" style={{ backgroundColor, top: index * 100 }} />
  );
};

export default function App() {
  const [arr, setArr] = useState(["blue", "red"]);
  useEffect(() => {
    setTimeout(() => {
      setArr(["red", "blue"]);
    }, 2000);
  }, []);
  return (
    <div className="App">
      {arr.map((backgroundColor, index) => (
        <Square
          index={index}
          backgroundColor={backgroundColor}
          key={backgroundColor}
        />
      ))}
    </div>
  );
}
.App {
  font-family: sans-serif;
  text-align: center;
  position: relative;
}

.square {
  transition: top 0.5s ease-out;
  width: 100px;
  height: 100px;
  position: absolute;
}

I've created codesandbox example of the issue: https://codesandbox.io/s/strange-framework-t2rq9

vaukalak
  • 81
  • 4
  • 1
    Can I confirm; you have an array set in state that you want to change the order of via a `setTimeout`? And that the transition required isn't working the way you expect it to? If you are relying on `index` to keep track of the position of each item you won't get what you're looking for. Each time a component is re-rendered, it's index will change meaning each colour will have a new and different index. You could try applying a unique id to it? – bopbopbop Jan 27 '22 at 13:22
  • @bopbopbop Thanks for your reply. I'm using the backgroundColor (a unique value) as a key. – vaukalak Jan 27 '22 at 16:36

0 Answers0