• Stars
    star
    4,080
  • Rank 10,642 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Effortless animation between DOM changes (eg. list reordering) using the FLIP technique.

React Flip Move

build status npm version npm monthly downloads

This module was built to tackle the common but arduous problem of animating a list of items when the list's order changes.

CSS transitions only work for CSS properties. If your list is shuffled, the items have rearranged themselves, but without the use of CSS. The DOM nodes don't know that their on-screen location has changed; from their perspective, they've been removed and inserted elsewhere in the document.

Flip Move uses the FLIP technique to work out what such a transition would look like, and fakes it using 60+ FPS hardware-accelerated CSS transforms.

Read more about how it works

demo

Current Status

React Flip Move is looking for maintainers!

In the meantime, we'll do our best to make sure React Flip Move continues to work with new versions of React, but otherwise it isn't being actively worked on.

Because it isn't under active development, you may be interested in checking out projects like react-flip-toolkit.

Demos

Installation

Flip Move can be installed with NPM or Yarn.

yarn add react-flip-move

# Or, if not using yarn:
npm i -S react-flip-move

A UMD build is made available for those not using JS package managers:

To use a UMD build, you can use <script> tags:

<html>
  <body>
    <script src="https://unpkg.com/react-flip-move/dist/react-flip-move.js"></script>
    <script>
      // Will be available under the global 'FlipMove'.
    </script>
  </body>
</html>

Features

Flip Move was inspired by Ryan Florence's awesome Magic Move, and offers:

  • Exclusive use of hardware-accelerated CSS properties (transform: translate) instead of positioning properties (top, left). Read why this matters.

  • Full support for enter/exit animations, including some spiffy presets, that all leverage hardware-accelerated CSS properties.

  • Ability to 'humanize' transitions by staggering the delay and/or duration of subsequent elements.

  • Ability to provide onStart / onFinish callbacks.

  • Compatible with Preact (should work with other React-like libraries as well).

  • Tiny! Gzipped size is <5kb! ⚑

Quickstart

Flip Move aims to be a "plug and play" solution, without needing a lot of tinkering. In the ideal case, you can wrap the children you already have with <FlipMove>, and get animation for free:

/**
 * BEFORE:
 */
const TopArticles = ({ articles }) => (
  {articles.map(article => (
    <Article key={article.id} {...article} />
  ))}
);

/**
 * AFTER:
 */
import FlipMove from 'react-flip-move';

const TopArticles = ({ articles }) => (
  <FlipMove>
    {articles.map(article => (
      <Article key={article.id} {...article} />
    ))}
  </FlipMove>
);

There are a number of options you can provide to customize Flip Move. There are also some gotchas to be aware of.

Usage with Functional Components

Functional components do not have a ref, which is needed by Flip Move to work. To make it work you need to wrap your functional component into React.forwardRef and pass it down to the first element which accepts refs, such as DOM elements or class components:

import React, { forwardRef } from 'react';
import FlipMove from 'react-flip-move';

const FunctionalArticle = forwardRef((props, ref) => (
  <div ref={ref}>
    {props.articleName}
  </div>
));

// you do not have to modify the parent component
// this will stay as described in the quickstart
const TopArticles = ({ articles }) => (
  <FlipMove>
    {articles.map(article => (
      <FunctionalArticle key={article.id} {...article} />
    ))}
  </FlipMove>
);

API Reference

View the full API reference documentation

Enter/Leave Animations

View the enter/leave docs

Compatibility

Chrome Firefox Safari IE Edge iOS Safari/Chrome Android Chrome
Supported βœ” 10+ βœ” 4+ βœ” 6.1+ βœ” 10+ βœ” βœ” 6.1+ βœ”

How It Works

Curious how this works, under the hood? Read the Medium post.


Wrapping Element

By default, Flip Move wraps the children you pass it in a <div>:

// JSX
<FlipMove>
  <div key="a">Hello</div>
  <div key="b">World</div>
</FlipMove>

// HTML
<div>
  <div>Hello</div>
  <div>World</div>
</div>

Any unrecognized props to <FlipMove> will be delegated to this wrapper element:

// JSX
<FlipMove className="flip-wrapper" style={{ color: 'red' }}>
  <div key="a">Hello</div>
  <div key="b">World</div>
</FlipMove>

// HTML
<div class="flip-wrapper" style="color: red;">
  <div key="a">Hello</div>
  <div key="b">World</div>
</div>

You can supply a different element type with the typeName prop:

// JSX
<FlipMove typeName="ul">
  <li key="a">Hello</li>
  <li key="b">World</li>
</FlipMove>

// HTML
<ul>
  <li key="a">Hello</li>
  <li key="b">World</li>
</ul>

Finally, if you're using React 16 or higher, and Flip Move 2.10 or higher, you can use the new "wrapperless" mode. This takes advantage of a React Fiber feature, which allows us to omit this wrapping element:

// JSX
<div className="your-own-element">
  <FlipMove typeName={null}>
    <div key="a">Hello</div>
    <div key="b">World</div>
  </FlipMove>
</div>

// HTML
<div class="your-own-element">
  <div key="a">Hello</div>
  <div key="b">World</div>
</div>

Wrapperless mode is nice, because it makes Flip Move more "invisible", and makes it easier to integrate with parent-child CSS properties like flexbox. However, there are some things to note:

  • This is a new feature in FlipMove, and isn't as battle-tested as the traditional method. Please test thoroughly before using in production, and report any bugs!
  • Flip Move does some positioning magic for enter/exit animations - specifically, it temporarily applies position: absolute to its children. For this to work correctly, you'll need to make sure that <FlipMove> is within a container that has a non-static position (eg. position: relative), and no padding:
// BAD - this will cause children to jump to a new position before exiting:
<div style={{ padding: 20 }}>
  <FlipMove typeName={null}>
    <div key="a">Hello world</div>
  </FlipMove>
</div>

// GOOD - a non-static position and a tight-fitting wrapper means children will
// stay in place while exiting:
<div style={{ position: 'relative' }}>
  <FlipMove typeName={null}>
    <div key="a">Hello world</div>
  </FlipMove>
</div>

Gotchas

  • Does not work with stateless functional components without a React.forwardRef, read more about here. This is because Flip Move uses refs to identify and apply styles to children, and stateless functional components cannot be given refs. Make sure the children you pass to <FlipMove> are either native DOM elements (like <div>), or class components.

  • All children need a unique key property. Even if Flip Move is only given a single child, it needs to have a unique key prop for Flip Move to track it.

  • Flip Move clones the direct children passed to it and overwrites the ref prop. As a result, you won't be able to set a ref on the top-most elements passed to FlipMove. To work around this limitation, you can wrap each child you pass to <FlipMove> in a <div>.

  • Elements whose positions have not changed between states will not be animated. This means that no onStart or onFinish callbacks will be executed for those elements.

  • Sometimes you'll want to update or change an item without triggering a Flip Move animation. For example, with optimistic updating, you may render a temporary version before replacing it with the server-validated one. In this case, use the same key for both versions, and Flip Move will treat them as the same item.

  • If you have a vertical list with numerous elements, exceeding viewport, and you are experiencing automatic scrolling issues when reordering an item (i.e. the browser scrolls to the moved item's position), you can add style={{ overflowAnchor: 'none' }} to the container element (e.g. <ul>) to prevent this issue.

Known Issues

  • Interrupted enter/leave animations can be funky. This has gotten better recently thanks to our great contributors, but extremely fast adding/removing of items can cause weird visual glitches, or cause state to become inconsistent. Experiment with your usecase!

  • Existing transition/transform properties will be overridden. I am hoping to change this in a future version, but at present, Flip Move does not take into account existing transition or transform CSS properties on its direct children.

Note on will-change

To fully benefit from hardware acceleration, each item being translated should have its own compositing layer. This can be accomplished with the CSS will-change property.

Applying will-change too willy-nilly, though, can have an adverse effect on mobile browsers, so I have opted to not use it at all.

In my personal experimentations on modern versions of Chrome, Safari, Firefox and IE, this property offers little to no gain (in Chrome's timeline I saw a savings of ~0.5ms on a 24-item shuffle).

YMMV: Feel free to experiment with the property in your CSS. Flip Move will respect the wishes of your stylesheet :)

Further reading: CSS will-change Property

Contributions

Contributors welcome! Please discuss new features with me ahead of time, and submit PRs for bug fixes with tests (Testing stack is Mocha/Chai/Sinon, tested in-browser by Karma).

There is a shared prepush hook which launches eslint, flow checks, and tests. It sets itself up automatically during npm install.

Development

This project uses React Storybook in development. The developer experience is absolutely lovely, and it makes testing new features like enter/leave presets super straightforward.

After installing dependencies, launch the Storybook dev server with npm run storybook.

This project adheres to the formatting established by airbnb's style guide. When contributing, you can make use of the autoformatter prettier to apply these rules by running the eslint script npm run lint:fix. If there are conflicts, the linter triggered by the prepush hook will inform you of those as well. To check your code by hand, run npm run lint.

Flow support

Flip Move's sources are type-checked with Flow. If your project uses it too, you may want to install typings for our public API from flow-typed repo.

npm install --global flow-typed # if not already
flow-typed install react-flip-move@<version>

If you're getting some flow errors coming from node_modules/react-flip-move/src path, you should add this to your .flowconfig file:

[ignore]
.*/node_modules/react-flip-move/.*

License

MIT

More Repositories

1

guppy

🐠A friendly application manager and task runner for React.js
JavaScript
3,268
star
2

use-sound

A React Hook for playing sound effects
JavaScript
2,614
star
3

waveforms

An interactive, explorable explanation about the peculiar magic of sound waves.
JavaScript
1,430
star
4

panther

Discover artists through an infinite node graph
JavaScript
919
star
5

new-component

βš› ⚑ CLI utility for quickly creating new React components. ⚑ βš›
JavaScript
699
star
6

redux-vcr

πŸ“Ό Record and replay user sessions
JavaScript
585
star
7

key-and-pad

🎹 Fun experiment with the Web Audio API 🎢
JavaScript
361
star
8

Tello

🐣 A simple and delightful way to track and manage TV shows.
JavaScript
329
star
9

tinkersynth

An experimental art project. Create unique art through serendipitous discovery.
JavaScript
282
star
10

beatmapper

A 3D editor for creating Beat Saber maps
JavaScript
271
star
11

blog

OLD VERSION of the joshwcomeau.com blog. Kept for historical purposes.
JavaScript
236
star
12

dark-mode-minimal

JavaScript
170
star
13

react-retro-hit-counter

πŸ†• Go back in time with this 90s-style hit counter.
JavaScript
162
star
14

redux-sounds

Middleware for playing audio / sound effects using Howler.js
JavaScript
130
star
15

dream-css-tool

JavaScript
119
star
16

react-collection-helpers

A suite of composable utility components to manipulate collections.
JavaScript
106
star
17

redux-favicon

Redux middleware that displays colourful notification badges in the favicon area.
JavaScript
105
star
18

nice-index

Atom package to rename `index.js` files to their parent directory names
CoffeeScript
82
star
19

react-europe-talk-2018

JavaScript
64
star
20

fakebook

A front-end Facebook clone, built with React and Redux
JavaScript
52
star
21

talk-2019

Slides for my 2019 talk, "Saving the Web 16ms at a Time"
JavaScript
52
star
22

understanding-react

Daily exploration of the React source code
42
star
23

talon-commands

Python
38
star
24

return-null

My React Europe 2017 lightning talk
JavaScript
35
star
25

explorable-explanations-with-react

JavaScript
35
star
26

word_dojo

JavaScript
18
star
27

react-boston-2018

My ReactBoston 2018 talk, The Case for Whimsy (Extended mix)
JavaScript
16
star
28

netlify-serverless-demo

JavaScript
16
star
29

css-for-js-flow-layout

HTML
14
star
30

whimsical-mail-client

JavaScript
14
star
31

ColourMatch

Search by Colour. Find photos with matching palettes.
CSS
12
star
32

talk-2020-react-europe

JavaScript
10
star
33

react-europe-workshop-confetti

JavaScript
10
star
34

plot

Experiments in pen plotting and generative art
JavaScript
9
star
35

sandpack-bundler-beta

JavaScript
8
star
36

react-play-button

JavaScript
7
star
37

react-europe-workshop-travel-site

JavaScript
7
star
38

deployed-screensaver

JavaScript
7
star
39

Uncover

πŸ“š Aggregate new releases from your favourite authors. Built with Vuejs and Node
Vue
6
star
40

redux-vcr-todomvc

ReduxVCR integrated into TodoMVC.
JavaScript
5
star
41

react-letter-animation

A take on Mike Bostock's General Update Pattern, using React Flip Move.
JavaScript
5
star
42

Perseus

Gather info about your stargazers. Uses the GitHub GraphQL API
JavaScript
5
star
43

gatsby-preview-demo

Gatsby starter for a Contentful project.
JavaScript
5
star
44

words-with-strangers-redux

A universal redux version of my Meteor attempt at Words with Friends (online scrabble).
JavaScript
4
star
45

leitner

Keep track of your position in the 64-day Leitner calendar
JavaScript
4
star
46

empowered-development-with-gatsby

My Gatsby Days LA 2020 talk!
HTML
4
star
47

react-floaters

Spring-based scroll animation experiment with React.js
JavaScript
4
star
48

datocms-Gatsby-Portfolio-Website-demo

CSS
4
star
49

tetris

A simple tetris clone, in React and Redux, using Redux Saga
JavaScript
4
star
50

katas

A bunch of CodeWars challenge solutions. Part of an ongoing blogging effort at https://medium.com/@joshuawcomeau
JavaScript
4
star
51

react-europe-workshop-twitter-like

JavaScript
4
star
52

joshbot

The Discord bot for my Course Platform's community.
JavaScript
3
star
53

unlikely-friends

Don't mind me. Experiments with Gatsby themes
JavaScript
3
star
54

dont_eat_here_toronto

A Chrome extension that displays Toronto DineSafe restaurant inspection stuff on Yelp restaurant pages.
JavaScript
3
star
55

script-search

Find code used on the world's top sites
Python
3
star
56

basilica

JavaScript
3
star
57

yger

πŸš€βš‘οΈ Blazing fast blog built with Gatsby and Cosmic JS πŸ”₯
JavaScript
3
star
58

gatsby-dark-mode

CSS
2
star
59

Mars-Rover-HTML

An HTML/CSS Mars Rover simulation
CSS
2
star
60

generic-portfolio

An example of a generic portfolio (what NOT to do)
HTML
2
star
61

ember-todo

Don't mind me! Just a toy app to familiarize myself with Ember
JavaScript
2
star
62

mono-gatsby-apps

CSS
2
star
63

Aracari

A simple-as-possible budgeting web app. Because I suck at budgeting.
JavaScript
2
star
64

temp-project-wordle

JavaScript
2
star
65

AngelHack_rando

1st Place @ AngelHack TO. Built in 24h.
Ruby
2
star
66

tree-shake-test

JavaScript
2
star
67

gatsby-personalization

CSS
2
star
68

ssr-repro

CSS
2
star
69

react-fluid-window-events

React component for smooth, efficient resize/scroll handling.
JavaScript
2
star
70

Percentext

a jQuery plugin that lets you style text elements by width.
JavaScript
2
star
71

RequestKittens

The only API ridiculous enough to let you find cats by emotion.
JavaScript
2
star
72

book-demo

Demo of Git fundamentals
2
star
73

HungryBelly

An extension of the winning 24-hour project created for AngelHackTO
Ruby
1
star
74

art

Generative art experiments
JavaScript
1
star
75

elevator-simulator

WIP
JavaScript
1
star
76

RAFT

Utility for efficient, organized window-level event handlers
JavaScript
1
star
77

CLYWmparison_blogembed

A Yoyo Comparison tool, used by Caribou Lodge Yoyo Works
JavaScript
1
star
78

TicTacToe

JavaScript
1
star
79

TeeVee

A simple Meteor app to help me keep track of which episodes of TV shows I've seen.
JavaScript
1
star
80

RequestKittensDocs

The documentation / sales site for the RequestKittens API
JavaScript
1
star
81

foodshow

A silly weekend project, using the Unsplash API to display a food slideshow.
JavaScript
1
star
82

egghead-optimized-images-1

HTML
1
star
83

react-simple-canvas

React components that replicate the SVG interface, but renders to an HTML5 Canvas
JavaScript
1
star
84

munsell-colors

JavaScript
1
star
85

joshwcc

My portfolio/blog. Nowhere close to done yet.
Ruby
1
star
86

egghead-optimized-images-2

HTML
1
star
87

learn-webgl

Experiments for education with WebGL. Don't mind me.
JavaScript
1
star
88

Crowdfunder

A Kickstarter clone. Bitmaker Labs final assignment.
Ruby
1
star
89

MEAN_stack_starter

A ready-to-go initialized MEAN stack with tons of customizations.
CSS
1
star
90

egghead-videos

JavaScript
1
star
91

pixelminer

An idle game (Γ  la cookie clicker), built to help me experiment with flowtype.
JavaScript
1
star
92

huddle

A Meteor app that aims to help patients have better access to their medical files, and get second opinions from physicians on the platform.
CSS
1
star
93

joshwcc_ver2

Attempt #2 at the joshw.cc portfolio site.
Ruby
1
star
94

Some-new-project

1
star
95

Advent-of-Code-2016

JavaScript
1
star
96

confetti-temp

JavaScript
1
star
97

redux-server-persist

JavaScript
1
star
98

Tori

Twitter, but for haikus.
JavaScript
1
star
99

classroom-q

Gatsby experimentation
CSS
1
star
100

fntest

CSS
1
star