Skip to content Skip to sidebar Skip to footer

React Spring - Animate Element Between Renders

I'm trying to get my head over React Spring. So I have some boxes, which I need to filter by an active index, and the idea is to animate the boxes rendering, but I'm only having an

Solution 1:

There may be better ways of doing this but here's a simple approach that works:

const boxes = [
  { label: "1", key: 0 },
  { label: "2", key: 1 },
  { label: "3", key: 2 }
];
//start with item 0 in the display boxes arrayconst displayBoxes = [];
displayBoxes.push(boxes[0]);

const transition = useTransition(displayBoxes, item => item.key, {
  from: { maxHeight: "0px", overflow: "hidden", margin: "0px 0px" },
  enter: { maxHeight: "100px", overflow: "hidden", margin: "5px 0px" },
  leave: { maxHeight: "0px", overflow: "hidden", margin: "0px 0px" }
});

consthandleBoxClick = n => () => {
  //empty the array
  displayBoxes = [];
  //then push in the new item
  displayBoxes.push(boxes[n]);
};

One feature of useTransition that is not immediately obvious to a newcomer is that the useTransition hook acts like an observer of the current state of the array you pass to it.

To achieve the effect you're looking for, I animated height from 0 to auto but that requires a way of getting the height in px and adds a further layer of complication. I like the idea of setting the height on the element and then using maxHeight to control its appearance.

Hope that helps.

Post a Comment for "React Spring - Animate Element Between Renders"