user3162979
user3162979

Reputation: 935

CSS animation and transformation in react-native

Just wondering if we can use CSS animation and transformation in react-native? i.e.

 <Image style={animateImage} / >

StyleSheet.create({

 animateImage {
   width: 100px;
   height: 100px;
   background: red;
   transition: width 3s;
   transition-delay: 1s;
 }

});

Upvotes: 25

Views: 39985

Answers (4)

Arvin Azs
Arvin Azs

Reputation: 208

You cannot be used directly because React Native doesn’t use a traditional DOM and CSS. Instead, React Native has its own styling system.

import React, { useRef, useEffect } from 'react';
import { Animated, StyleSheet, View, Image } from 'react-native';

const AnimatedImage = () => {
  const widthAnimation = useRef(new Animated.Value(100)).current;

  useEffect(() => {
    Animated.timing(widthAnimation, {
      toValue: 200, 
      duration: 3000, 
      delay: 1000, 
      useNativeDriver: false, 
    }).start();
  }, []);

  return (
    <View style={styles.container}>
      <Animated.Image
        style={[styles.image, { width: widthAnimation }]} // Bind width to animated value
        source={{ uri: 'https://via.placeholder.com/150' }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    height: 100, // Fixed height
    resizeMode: 'contain',
  },
});

export default AnimatedImage;

Upvotes: 0

kacperkapusciak
kacperkapusciak

Reputation: 71

React Native Reanimated 4.0 comes with a support for an API similar to CSS Animations and Transitions. Currently available in Beta.

function App() {
  return (
    <Animated.View
      style={{
        transitionProperty: 'width',
        transitionDuration: 300,
      }}
    />
  );
}

Check out the Reanimated 4 documentation for more information.

Upvotes: 4

No, you can't use CSS animations and transformations in React Native. There is a Keyframes library for React-Native called react-native-facebook-keyframes. It might be what you need instead.

Upvotes: 2

Viktor Sec
Viktor Sec

Reputation: 3050

No, you cannot. React Native's Stylesheet properties are pretty limited when compared with vanilla CSS.

For animations look into the Animated API.

Upvotes: 19

Related Questions