64

I have a list of items with scores, ordered by scores, rendered by react.js as a vertically-oriented list of rectangular items (highest scores at top). Hovers and other clicks on the individual items may show/hide extra info, changing their vertical height.

New information arrives that changes the scores, slightly, making some items rank higher and others lower after a re-sort. I'd like the items to simultaneously animate to their new positions, rather than appear in their new locations instantly.

Is there a recommended way to do this in React.js, perhaps with a popular add-on?

(In a similar past situation using D3, a technique I've used was roughly:

  1. Display the list with item DOM nodes in their natural order, with relative positioning. With relative positioning, other small changes – CSS or JS-triggered – to individual items' extent shift others as expected.
  2. Mutate all the DOM nodes, in a single step, to have their actual relative-coordinates as new absolute coordinates – a DOM change that causes no visual change.
  3. Re-order the item DOM nodes, within their parent, to the new sort order – another DOM change that causes no visual change.
  4. Animate all nodes' top-offsets to their new calculated values, based on the heights of all preceding items in the new ordering. This is the only visually-active step.
  5. Mutate all item DOM nodes back to non-offset relative-positioning. Again, this causes no visual change, but the now-relatively-positioned DOM nodes, in the natural ordering of the underlying list, will handle internal hover/expand/etc style changes with proper shifting.

Now I'm hoping for a similar effect in a React-ish way...)

4
  • 5
    you may want to look at: github.com/chenglou/react-tween-state (I have never used it so far, but was planing to many times :) ) Nov 29, 2014 at 10:23
  • Indeed it was seeing that react-tween-state that reminded me I've been wondering about this for a while, and prompted my question. It looks like it might be usable, with some multi-step hackery like my prior D3 approach... but still hoping there might be a strongly-recommended/optimized way already out there in the React community.
    – gojomo
    Dec 3, 2014 at 21:19
  • 2
    I just found this. It looks like it's pretty close to what you've described... and it has a really good feel to it. MixItUp Dec 4, 2014 at 19:53
  • 1
    MixItUp is pretty! And, very much like the visual effect I'm looking for. (I'd previously used, and even bought a license for, Metafizzy's similar Isotope before settling on the D3-approach roughly described above.) But, now I'm specifically looking for a React.js-based (and free/open source) approach. So in a way the question is: how to do MixItUp/Isotope-like effects in a React-friendly way?
    – gojomo
    Dec 5, 2014 at 1:04

9 Answers 9

69

I just released a module to tackle exactly this problem

https://github.com/joshwcomeau/react-flip-move

It does a few things differently than Magic Move / Shuffle:

  1. It uses the FLIP technique for hardware-accelerated 60FPS+ animations
  2. It offers options to "humanize" the shuffle by incrementally offsetting delay or duration
  3. It handles interruptions gracefully, no weird glitch effects
  4. Bunch of other neat stuff like start/finish callbacks

Check out the demos:

http://joshwcomeau.github.io/react-flip-move/examples/#/shuffle

7
  • This looks great. Definitely going to give this a try, thanks.
    – inostia
    Dec 8, 2016 at 22:39
  • 3
    Couple years later, this module is still going strong :) In the time since, we've introduced enter/leave animations, added more props for customizability, improved performance, and shrunk the bundle size (under 5kb gzip now!) Jan 27, 2018 at 10:52
  • Hey, Joshua, I really love your idea. I am using the component right now. Got a question here, is there a way to disable the flip? I need to disable it in certain conditions Jun 18, 2020 at 10:17
  • 1
    NVM, found myself the answer, (the disableAllAnimations prop ) Jun 18, 2020 at 14:16
  • Just came back to say "This is amazing!". Very easy setup Nov 8, 2023 at 16:20
9

React Shuffle is solid and up to date. It's inspired by Ryan Florences Magic Move demo

https://github.com/FormidableLabs/react-shuffle

1
  • FormidableLabs/react-shuffle is no longer maintained.
    – Danon
    Aug 14, 2020 at 18:10
9

I realise this is a bit of an old question and you've probably found a solution by now, but for anyone else coming across this question, check out the MagicMove library by Ryan Florence. It's a React library to handle the exact scenario you describe: https://github.com/ryanflorence/react-magic-move

See it in action: https://www.youtube.com/watch?v=z5e7kWSHWTg#t=424

Edit: This is broken in React 0.14. See React Shuffle as an alternative, as suggested by Tim Arney below.

3
  • Wow, that looks like exactly the right thing! I've tinkered with other possible approaches, but not deployed any yet, so this is a great help.
    – gojomo
    Mar 13, 2015 at 23:55
  • That is quite impressive! There do seem to be some issues (see github) with React 0.13 though, and i suppose this wont change until at least React 0.14 Apr 30, 2015 at 12:54
  • Doesn't with 0.14 unfortunately: github.com/ryanflorence/react-magic-move/issues/15 Jan 7, 2016 at 8:21
6

Late to the party here, but we just released AutoAnimate which allows you to add animations for elements entering, leaving, or moving within a DOM element with a single line of code. Works with React, Vue, or any other Javascript framework and is less than 2kb in size.

Open-source and MIT licensed, hope it's helpful!

5

I didn't want to use a third-part library for my animations so I implemented the "FLIP" animation technique using React lifecycle methods getSnapshotBeforeUpdate() and componentDidUpdate().

When the list item's props.index changes the old position is captured in getSnapshotBeforeUpdate() and in componentDidUpdate() the css transform: translateY() is applied so that the item appears to be animating from old position to current position.

class TreeListItem extends Component {

  constructor(props) {
    super(props);
    this.liRef = React.createRef();
  }

  getSnapshotBeforeUpdate(prevProps) {
    if (prevProps.index !== this.props.index) {
      // list index is changing, prepare to animate
      if (this.liRef && this.liRef.current) {
        return this.liRef.current.getBoundingClientRect().top;
      }
    }
    return null;
  }


  componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevProps.index !== this.props.index && snapshot) {
      if (this.liRef && this.liRef.current) {
        let el = this.liRef.current;
        let newOffset = el.getBoundingClientRect().top;
        let invert = parseInt(snapshot - newOffset);
        el.classList.remove('animate-on-transforms');
        el.style.transform = `translateY(${invert}px)`;
        // Wait for the next frame so we
        // know all the style changes have
        // taken hold.
        requestAnimationFrame(function () {
          // Switch on animations.
          el.classList.add('animate-on-transforms');
          // GO GO GOOOOOO!
          el.style.transform = '';
        });
      }
    }
  }

  render() {
    return <li ref={this.liRef}>
    </li >;
  }
}

class TreeList extends Component {

  render() {
    let treeItems = [];
    if (this.props.dataSet instanceof Array) {
      this.props.dataSet.forEach((data, i) => {
        treeItems.push(<TreeListItem index={i} key={data.value} />)
      });
    }

    return <ul>
      {treeItems}
      </ul>;
  }
}
.animate-on-transforms {
  /* animate list item reorder */
  transition: transform 300ms ease;
}

2
  • 2
    My favorite answer in this list because it doesn't require a third party library to achieve what the OP is asking for.
    – JoeMoe1984
    Aug 26, 2020 at 15:47
  • 1
    This should be marked as the best answer, it's simple, clean and doesn't depend on any third-party lib.
    – ArthurG
    May 22, 2021 at 22:38
2

The best way I can think of to accomplish this off the top of my head would be to first make sure that you give every one of your elements a key as described here:

http://facebook.github.io/react/docs/multiple-components.html#dynamic-children

Next I would define CSS3 animation similar to this:

Animating lists with CSS3

Basically in your render function you would calculate where the element is suppose to go, ReactJS will place the element where it's suppose to be (make sure you give each element the same key every time! This is important to make sure ReactJS reuses your DOM element properly). In theory at least, the CSS should take care of the rest of the animation for you outside of reactjs/javascript.

Disclamer... I've never actually tried this ;)

2
  • 1
    Doesn't work. It looks like elements get removed from the dom at some point, breaking css transitions. jsfiddle.net/se6mqm3p/1 Dec 10, 2015 at 22:54
  • 3
    Interesting. Looks like react doesn't always respect the keys. You can do something like this though: jsfiddle.net/se6mqm3p/2 I basically kept the ordering on the elements the same no matter what. Not exactly what i was thinking originally, but it can work.
    – Chris
    Dec 14, 2015 at 18:24
0

I just found this library: https://www.npmjs.com/package/react-animated-list, Its very amazing, You just have to pass the children:

import { AnimatedList } from 'react-animated-list';
import { MyOtherComponent } from './MyOtherComponent';

const MyComponent = ({myData}) => (
  <AnimatedList animation={"grow"}>
    {otherComponents.map((c) => (
      <MyOtherComponent key={c.id} />
    ))}
  </AnimatedList>
)

Demo: https://codesandbox.io/s/nifty-platform-dj1iz?fontsize=14&hidenavigation=1&theme=dark

Boom it will work for you.

1
  • This question is about list re-ordering, not adding/removing elements. Moving element indexes end sup being a different problem. Apr 24, 2022 at 6:31
-1

Because the position of an element depends heavily on the DOM engine, I find it really hard to implement tweening and animating in a pure way within React components. If you want to do it cleanly, I think you need at least: a Store to hold the current position of an element, a Store to hold the next position of an element (or combine it with the previous store), and a render() method that applies the offset margins per element until in the final frame, the next positions become current. How you calculate the next positions in the first place is also a challenge. But given that the elements only swap positions, you could use the Store with the current positions to swap element #0 with element #1, by swapping their offsets in the next positions Store.

In the end it's easier to just use an external library to manipulate the elements' margins after they're rendered.

-4

Just use ReactCSSTransitionGroup. It's built into the React with Addons package and is perfect for this use case! Just make sure that the component on which you apply the transition has already mounted to the DOM. Use the CSS that is in the linked example for a nice fading transition.

2
  • 4
    Thanks, but from my reading of that link, it only handles entry/exit of items – not re-sort to a new position. Nor do I see a way to extend it, without the kind of outside-React positional-calculations mentioned in the question or other answers. (A series of fade-ins/fade-outs, even simultaneous, isn't the effect I'm seeking.)
    – gojomo
    Feb 18, 2015 at 5:30
  • 1
    This actually isn't a very functional solution at the moment. In addition to the limitations it is extremely buggy due to its reliance on browser events that don't always fire in many circumstances (see github.com/facebook/react/issues/1326). What's worse is that there doesn't seem to be a timeline to even fix it (at least according to that issue thread). Looks like we'll have to wait for React to introduce a more robust way for native transition support. Jun 2, 2015 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.