React Motion - Tuong-Nguyen/JavaScript-Structure GitHub Wiki

Concepts

Spring

Usage

Install

npm install --save react-motion

APIs

spring

Specify the how to animate to the destination value

spring(val: number, config?: SpringHelperConfig) => OpaqueConfig
  • val: value number
  • config:
    • stiffness: default is 170
    • damping: default is 26
    • precision: default is 0.01

Check how stiffness and damping affect the spring

presets

Use common configurations with presets

{
  noWobble: {stiffness: 170, damping: 26}, // the default, if nothing provided
  gentle: {stiffness: 120, damping: 14},
  wobbly: {stiffness: 180, damping: 12},
  stiff: {stiffness: 210, damping: 20}
}

<Motion />

Syntax

<Motion defaultStyle={{PlainStyle}} style={{propetyX: OpaqueConfig, ...}}>
 {children}
</Motion>
  • defaultStyle: optional, initial numbers. During subsequent renders, it's ignored. The value will be interpolated from current ones to destination ones
  • style: destination numbers of style.
  • children(interpolatedStyle) is a function that return one React element to render

Sample

          <Motion defaultStyle={{h:0}} style={{h: spring(200)}}>
            {
              ({h}) => <div className={classes.div} style={{width: h}}>
                {'Default is noWobble'}
              </div>
            }
          </Motion>
  • style={{h: spring(200)}}: h is interpolated to 200, if style={{h: 200}}, h is jumped to 200
  • style={{width: h}}: at a certain time interpolatedStyle is {h: 121.2} that will be applied to width attribute of the div

<StaggeredMotion />

Animates a collection of items where the values of an item depends on previous one.

Syntax

<StaggeredMotion defaultStyles={[{PlainStyle}, {PlainStyle},...]} 
                 styles={(previousInterpolatedStyles) => { return Styles[];}}>
 {children}
</StaggeredMotion>
  • defaultStyles: optional, similar to Motion's defaultStyle but an array of them.
  • styles(previousInterpolatedStyles => { return Styles[]})
    • previousInterpolatedStyles: previous interpolating (array) styles. It's undefined at first render if defaultStyles was not defined.
  • children(interpolatedStyles): similar to Motion's children but argument is an array of interpolatedStyle.

Sample

<StaggeredMotion
  defaultStyles={[{h: 0}, {h: 0}, {h: 0}]}
  styles={prevInterpolatedStyles => prevInterpolatedStyles.map((_, i) => {
    return i === 0
      ? {h: spring(100)}
      : {h: spring(prevInterpolatedStyles[i - 1].h)}
  })}>
  {interpolatingStyles =>
    <div>
      {interpolatingStyles.map((style, i) =>
        <div key={i} style={{border: '1px solid', height: style.h}} />)
      }
    </div>
  }
</StaggeredMotion>

Example Code

⚠️ **GitHub.com Fallback** ⚠️