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. TherandomRGB()
method returns one random value between0
and255
. ThegetRandomColor()
method uses the random values to create a color string likergb(103,72,17)
. - The
currentColor
variable is initialized using thegetRandomColor()
method. It is a state variable and it can be updated with thesetCurrentColor()
method. Updating this value will rerender the component. - The background color property,
backgroundColor
is assigned ascurrentColor
. So, it will show a random color to theView
. - On pressing the
TouchableWithoutFeedback
component, it assigns a new value to thecurrentColor
variable by using thesetCurrentColor
method. As this is a state variable, it will rerender theView
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.
You can use the above approach to update the background color or any other property of any component dynamically.
You might also like:
- React native example to create Text with different colors or multicolored Text
- How to remove yellow warning box in React Native
- How to hide the keyboard on touch outside in react native
- Handling keyboard with react-native ScrollView
- How to show pdf files in react native applications
- How to add scroll to top to a FlatList in ReactNative app