DEV Community

loading...

Simple animated ball in react-native

merlier profile image Merlier ・1 min read

I will just figure out here some of my progress in the animated world of react-native.
Just begin by moving a ball in the screen very simply!

The code of the whole app build here is available at https://github.com/Merlier/rn_example_animated_ball

Get started

Requirements:

  • react-native >= 0.60

First just init a new react-native project:

$ npx react-native init rn_example_animated_ball
Enter fullscreen mode Exit fullscreen mode

Create a simple ball

in your app.js:

import React from 'react';
import {StyleSheet, View, Button} from 'react-native';

const App: () => React$Node = () => {
  return (
    <View style={styles.container}>
      <Button onPress={() => console.log('run')} title="RUN" />
      <View style={styles.ball} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  ball: {
    width: 100,
    height: 100,
    borderRadius: 100,
    backgroundColor: 'red',
  },
});
Enter fullscreen mode Exit fullscreen mode

Now just move...

in your app.js:

import React, {useRef} from 'react';
import {StyleSheet, Dimensions, View, Animated, Button} from 'react-native';

const App: () => React$Node = () => {
  const windowWidth = Dimensions.get('window').width;
  const initPosition = {
    x: parseInt(windowWidth / 2) - 50,
    y: 0,
  };

  const position = useRef(new Animated.ValueXY(initPosition)).current;

  const animate = () => {
    Animated.spring(position, {
      toValue: {x: initPosition.x, y: 350},
      speed: 4,
      useNativeDriver: false,
    }).start(() => {
      position.setValue(initPosition);
    });
  };

  return (
    <View style={styles.container}>
      <Button onPress={animate} title="RUN" />
      <Animated.View style={[position.getLayout(), styles.ball]} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  ball: {
    width: 100,
    height: 100,
    borderRadius: 100,
    backgroundColor: 'red',
  },
});
Enter fullscreen mode Exit fullscreen mode
$ npx react-native run-android
Enter fullscreen mode Exit fullscreen mode

Alt Text

Alt Text

It's just the basics but it's the first step ;)
Have fun
:)

Discussion (0)

pic
Editor guide