TIMEX
TIMEX

Reputation: 272254

In react-native, how can I make a View's background color change to another color, and then fade out?

I'd like the View to change to dark blue, and then slowly fade back to normal (aka white).

How can this be done?

Upvotes: 0

Views: 639

Answers (1)

Usama Moin
Usama Moin

Reputation: 203

You can use animated by react-native. Here's a sample code to achieve what you are looking for

import * as React from "react";
import { Text, View, StyleSheet, Animated } from "react-native";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colorAnimation: new Animated.Value(0)
    };
  }

  componentDidMount() {
    const { colorAnimation } = this.state;

    {
      /* Change Color To blue */
    }
    Animated.timing(colorAnimation, {
      toValue: 255,
      duration: 1000 //Animation Duration
    }).start();

    {
      /*  After 1 second change color back to white */
    }

    setInterval(() => {
      Animated.timing(colorAnimation, {
        toValue: 0,
        duration: 3000 //Animation Duration
      }).start();
    }, 1000);
  }

  render() {
    const interpolatedColor = this.state.colorAnimation.interpolate({
      inputRange: [0, 255],
      outputRange: ["rgb(255,255,255)", "rgb(0, 0, 139)"]
    });
    return (
      <Animated.View
        style={[styles.container, { backgroundColor: interpolatedColor }]}
      ></Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    padding: 8
  }
});

You can view the demo here.

Upvotes: 2

Related Questions