Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native state change transitions

What is the best pattern, in react native, to animate components on state change?

For example I have a list of elements and tapping on one I want it to disappear and the ones below him to 'get up' filling the missing space

How can I make the transition smooth?

like image 313
nicecatch Avatar asked May 30 '18 10:05

nicecatch


People also ask

How do you animate when React state changes?

You can use CSS classes to animate in React import React, { useState } from 'react'; import classNames from 'classnames'; import styles from './App. module. css'; const App = () => { const [animate, setAnimate] = useState(false); const handleClick = () => setAnimate(!


1 Answers

React-natives own animated API works really well.

Basically you have a value in state, which you connect with a style props, and change that value over time. (for examples follow link)

For smooth animations use usenativedriver (not always possible) and also, make sure you don't have debugger runnning in emulated/real device

EDIT: 2018-05-31

This is an example of how I've used it. Probably exist other ways of doing it

import { Animated, Text} from 'react-native';

class ShowCaseAnimation extends Component {

  state = { 
    animations: {
      height: new Animated.Value(0),
      fade: new Animated.Value(0),
    }
  }

  componentDidMount() {
    const { height, fade } = this.state.animations;
    if (this.props.animate) {
      doneAnimation({ height, fade }).start(() => {
        // Do stuff after animations
      });
    }
  }

  render() {
    const { animations } = this.state; 
    return (
      <Animated.View 
        style={{
          height: animate? animations.height : 300, 
          opacity: animate? animations.fade: 1,
          // other styling 
        }}
      >
        <Text> All your base are belong to us </Text>
      </Animated.View>
    );
  }
}

*doneAnimation: *

import { Animated, Easing } from 'react-native';

export const doneAnimation = ({ height, fade }) => Animated.parallel([
  Animated.timing(height, {
    toValue: 300,
    easing: Easing.elastic(),
    duration: 500,
    delay: 1500,
  }),
  Animated.timing(fade, {
    toValue: 1,
    easing: Easing.ease,
    duration: 1000,
    delay: 1500,
  }),
]);

export default doneAnimation;

doneAnimation will change the state and perform the described animations.

like image 57
Jakob Göran Thomasson Avatar answered Nov 08 '22 21:11

Jakob Göran Thomasson