• Stars
    star
    754
  • Rank 60,205 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

Lightweight React component for animating height using CSS transitions. Slide up/down the element, and animate it to any specific height.

React Animate Height

npm version npm downloads

No dependencies React component for animating height using CSS transitions. Slide an element up and down or animate it to any specific height. Content's opacity can be optionally animated as well (check animateOpacity prop bellow).

CSS classes are applied in specific animation states, check animationStateClasses prop.

Changelog

Version 3

This is version 3.x branch, rewritten to hooks, which means you'll need React version 16.8 or newer.

For version 2.x, check v2 branch

Breaking changes:

  • Callback names changed (to avoid clashing with the native ones):
    • onAnimationStart -> onHeightAnimationStart
    • onAnimationEnd -> onHeightAnimationEnd

Demo

Live demo: muffinman.io/react-animate-height

Because multiple people asked how to animate list items, I created this simple example for that as well.

To build the examples locally, run:

npm install
npm start

Then open http://127.0.0.1:8000/ in your browser of choice browser.

Or play with this sandbox.

Quick start

Get it from npm

$ npm install --save react-animate-height

Import and use it in your React app.

import React, { useState } from 'react';
import AnimateHeight from 'react-animate-height';

const Example = () => {
  const [height, setHeight] = useState(0);

  return (
    <div>
      <button
        aria-expanded={height !== 0}
        aria-controls="example-panel"
        onClick={() => setHeight(height === 0 ? 'auto' : 0)}
      >
        {height === 0 ? 'Open' : 'Close'}
      </button>

      <AnimateHeight
        id="example-panel"
        duration={500}
        height={height} // see props documentation below
      >
        <h1>Your content goes here</h1>
        <p>Put as many React or HTML components here.</p>
      </AnimateHeight>
    </div>
  );
};

Props

  • height: numeric or percentage value (ie. '50%') or 'auto', required

    When changed, element height will be animated to that height.
    To slide up use 0, for slide down use 'auto'

  • duration: integer, default: 500

    Duration of the animation in milliseconds

  • delay: integer, default: 0

    Animation delay in milliseconds

  • easing: string, default: 'ease'

    CSS easing function to be applied to the animation

  • id: string

    HTML id attribute.

  • className: string

    CSS class to be applied to the element

    Please note that you shouldn't apply properties that are messing with the layout (like display, height...), as these might break height calculations

  • ref: React.MutableRefObject<HTMLDivElement | null>

    Reference to the main div element.

      const wrapperDiv = useRef<HTMLDivElement | null>(null);
    
      <AnimateHeight ref={wrapperDiv}>
  • contentRef: React.MutableRefObject<HTMLDivElement | null>

    Reference to the content div element.

      const contentDiv = useRef<HTMLDivElement | null>(null);
    
      <AnimateHeight contentRef={contentDiv}>
  • style: object

    CSS style object, it will be merged with inline styles of the component

    Please note that you shouldn't apply properties that are messing with the layout (display, height are omitted from the type already), as these might break height calculations

  • contentClassName: string

    CSS class to be applied to content wrapper element

    Please note that you shouldn't apply properties that are messing with the layout (like display, height...), as these might break height calculations

  • animationStateClasses: object

    Object containing CSS class names for animation states, default:

    {
      animating:                  'rah-animating',
      animatingUp:                'rah-animating--up',
      animatingDown:              'rah-animating--down',
      static:                     'rah-static',
      animatingToHeightZero:      'rah-animating--to-height-zero',
      animatingToHeightAuto:      'rah-animating--to-height-auto',
      animatingToHeightSpecific:  'rah-animating--to-height-specific',
      staticHeightZero:           'rah-static--height-zero',
      staticHeightAuto:           'rah-static--height-auto',
      staticHeightSpecific:       'rah-static--height-specific',
    }
    

    Please note that this one will be merged with the default object and cached when component is created, so changing it afterwards will have no effect.

  • onHeightAnimationStart: function

    Callback which will be called when animation starts.

    This first argument passed to this callback is an object containing newHeight, the pixel value of the height at which the animation will end.

  • onHeightAnimationEnd: function

    Callback which will be called when animation ends.

    This first argument passed to this callback is an object containing newHeight, the pixel value of the height at which the animation ended.

  • applyInlineTransitions: boolean, default: true

    If this flag is set to false only CSS classes will be applied to the element and inline transition styles will not be present.

  • animateOpacity: boolean, default: false

    If set to true content will fade-in (and fade-out) while height is animated.

  • aria-hidden: boolean

    By default, library will set aria-hidden to true when height is zero. If you wish to override it, you can pass the prop yourself.

Additional props will be passed to the wrapper div, to make adding attrs like aria-* easier.

Accessibility

Library will hide the content using display: hidden when height props is 0. It will also apply aria-hidden="true" in the same case, but you can override it by passing aria-hidden prop yourself.

When using a button to toggle height, make sure you add aria-expanded and aria-controls to make everything accessible. Here's an example:

<button
  aria-expanded={ height !== 0 }
  aria-controls="example-panel" // it has to match the id passed to AnimateHeight
  onClick={ toggleHeight } // your click handler that toggles height
  // ... all other props
>
  Toggle
</button>

<AnimateHeight id="example-panel">
  Content
</AnimateHeight>

Reduced motion

Component checks for prefers-reduced-motion on start and disables animations if it is set to true. Please note that component doesn't listen for potential changes of prefers-reduced-motion option.

Animate height on content change

You can achieve this by using ResizeObserver.

Here is an example:

Gotchas

Collapsing margins

While it is animating, component has overflow: hidden. When the animation is finished and height is set to "auto", overflow: hidden is removed. At that moment, any margins you have on the content inside AnimateHeight will collapse, causing content to "jump". To avoid this, just use padding inside the AnimateHeight instead of margins.

Bounded flexboxes

If AnimateHeight is a flex child and it's parent has a fixed height, animation won't work. To fix this, you just need to add the following CSS rule to the AnimateHeight instance.

flex-shrink: 0;

You can do it by passing a className or directly in the style prop

<AnimateHeight style={{flexShrink: 0}}>

Check the issue #89 for the example and more details.

License

MIT

More Repositories

1

react-plx

React parallax component, powerful and lightweight
TypeScript
686
star
2

skyblue

CSS framework (made with SASS)
HTML
453
star
3

html-canvas-video-player

Play inline videos on iPhone with HTML canvas player.
JavaScript
426
star
4

animated-scroll-to

Lightweight scroll to function with a powerful API.
TypeScript
381
star
5

ThinkPad-Fan-Control

App for managing fan speeds on ThinkPad laptops on Linux
C
119
star
6

webpack-babel-react-revisited

Example repo for webpack/babel/react tutorial - https://stanko.github.io/webpack-babel-react-revisited
JavaScript
94
star
7

mobile-chrome-vh-fix

HTML
75
star
8

react-slider

Simple react slider, with touch support and 0 dependencies
JavaScript
65
star
9

react-image-filter

Lightweight React component, for applying color filters on images, works in all modern browsers plus IE10+ and Edge.
JavaScript
57
star
10

retro-frame

JavaScript
42
star
11

sektor

JavaScript library for creating SVG circle sectors and arcs
JavaScript
41
star
12

neon

Generative art piece made using 2d vector field
JavaScript
37
star
13

offset-polygon

Small, no dependency library for offsetting polygons.
TypeScript
32
star
14

rocketScroll

Pure small JavaScript scroll bar script. Support native mouse wheel scroll. Easy customizable css. Works even in IE8+.
JavaScript
32
star
15

awesome-web-development

List of useful articles and libraries for web development (basically links from our company slack dev channel)
32
star
16

react-window-decorators

Two decorators (higher order components) that inject "window" scroll position, dimensions, orientation and breakpoint to your component's props.
JavaScript
32
star
17

window-scroll-manager

60fps window scroll tracking event
JavaScript
31
star
18

vertigo

A tool that transforms raster images into vectors using two distinct shaders - circular dot grid and variable-width spiral.
TypeScript
31
star
19

aria-progress-range-slider

Fully accessible, lightweight progress bar / range slider component
TypeScript
23
star
20

keen

My personal, minimal setup for building and releasing npm packages
TypeScript
15
star
21

linea

JavaScript vector 3D engine
Go
14
star
22

react-ratio

React aspect ratio component
JavaScript
14
star
23

jquery.rainbowJSON

JSON pretty print, jquery plugin
JavaScript
10
star
24

react-tutorial

JavaScript
8
star
25

Stanko.github.io

My personal blog
SCSS
8
star
26

has-tabbed

Small helper for enabling nicer focus behaviour
HTML
5
star
27

timePicker

Plain JavaScript time picker.
JavaScript
4
star
28

rocketPageFlip

jQuery lib for page turning effect
CSS
4
star
29

react-window

React components that simplify the management of window and body event listeners.
TypeScript
4
star
30

letters-from-sarajevo

Adaptation of the book "Letters From Sarajevo" for web
HTML
4
star
31

generative-swirls

JavaScript
4
star
32

pulsar

Micro creative coding playground
TypeScript
4
star
33

generative-utils

TypeScript
3
star
34

ui-colors-from-an-image

TypeScript
3
star
35

generative-breathe

JavaScript
3
star
36

cca

Create Coding Amsterdam
3
star
37

jquery.responsiveFonts

JQuery plugin which makes fonts responsive
HTML
2
star
38

tailor

A developer tool which tries to simplify inspecting spacings on websites
TypeScript
2
star
39

weekly-code-challenge

JavaScript
1
star
40

slice-pixelate-image

JavaScript
1
star
41

LittleWing

Fullscreen backgrounds jQuery plugin
JavaScript
1
star
42

redux-spark

(Deprecated) Helps significantly reduce amount of boilerplate code when using Redux and Redux Saga
TypeScript
1
star
43

generative-init

JavaScript
1
star
44

cube-3D-rotate-grid

JavaScript
1
star