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, it will have only one Screen with one square 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 in styles to add a background color to a view.

The below program does that:

import React, { 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() + ')';

const 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
  }
});

export default App;

Here,

  • The getRandomColor method is returning a random color. randomRGB returns one random value between 0 and 256.
  • currentColor is initialized by using the getRandomColor method.
  • We are setting the backgroundColor of the View , i.e. currentColor.
  • The TouchableWithoutFeedback is changing the background color of the view by using getRandomColor.

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 might also like: