How to change the background color of a View dynamically in React Native

How to change the background color of a View dynamically in React Native:

This post will show you how to change the background color of a View dynamically in React Native. We will create one small application that will have only one screen with one View with a background color. If we click on it, it will change the color to some random color. You can keep clicking on it and it will again change to a different color.

Dynamically change the view color:

We can use the backgroundColor property to add a background color to a View. If the value of the property is assigned with a state variable, updating the state variable will update the background color of the View.

Let me show you how it can be done with an example:

import { useState } from 'react';
import {
  SafeAreaView,
  View,
  StyleSheet,
  StatusBar,
  TouchableWithoutFeedback,
} from 'react-native';

const randomRGB = () => Math.floor(Math.random() * 256);

const getRandomColor = () =>
  'rgb(' + randomRGB() + ',' + randomRGB() + ',' + randomRGB() + ')';

export default function App() {
  const [currentColor, setCurrentColor] = useState(getRandomColor());

  return (
    <SafeAreaView style={styles.container}>
      <TouchableWithoutFeedback
        onPress={() => setCurrentColor(getRandomColor())}>
        <View style={[styles.view, { backgroundColor: currentColor }]} />
      </TouchableWithoutFeedback>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
    alignItems: 'center',
  },
  view: {
    width: 100,
    height: 100,
  },
});

Download it on GitHub

  • The getRandomColor() method is returning a random color. The randomRGB() method returns one random value between 0 and 255. The getRandomColor() method uses the random values to create a color string like rgb(103,72,17).
  • The currentColor variable is initialized using the getRandomColor() method. It is a state variable and it can be updated with the setCurrentColor() method. Updating this value will rerender the component.
  • The background color property, backgroundColor is assigned as currentColor. So, it will show a random color to the View.
  • On pressing the TouchableWithoutFeedback component, it assigns a new value to the currentColor variable by using the setCurrentColor method. As this is a state variable, it will rerender the View component with the new color.

If you run this app, it will show a View at the center of the screen. If you tap on it, it will change the color randomly.

react native change view background color example

You can use the above approach to update the background color or any other property of any component dynamically.

You might also like: