How to Generate Random Colors in React Native?
Sep 23, 2022 . Admin
This article will give you example of generate random colors in react native. if you have question about random colors in react native then I will give simple example with solution. it's simple example of flatlist generate random colors in react native. We will look at example of react native generate random colors example.
In this example,We will learn to random color in react native.you can generate random colors and set them as background colors in react native.
Step 1: Download ProjectIn the first step run the following command to create a project.
expo init ExampleAppStep 2: App.js
In this step, You will open the App.js file and put the code.
import React from 'react'; import {View, FlatList, StyleSheet, Text} from 'react-native'; const DATA = [ { id: '1', title: 'First', }, { id: '2', title: 'Second', }, { id: '3', title: 'Third', }, { id: '4', title: 'Fourth', }, { id: '5', title: 'Fifth', }, ]; const generateColor = () => { const randomColor = Math.floor(Math.random() * 16777215) .toString(16) .padStart(6, '0'); return `#${randomColor}`; }; const App = () => { return ( <View style={styles.container}> <FlatList data={DATA} renderItem={({item}) => ( <View style={[styles.item, {backgroundColor: generateColor()}]}> <Text style={styles.title}>{item.title}</Text> </View> )} keyExtractor={item => item.id} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 25 }, item: { height: 100, alignItems: 'center', justifyContent: 'center', }, title: { fontSize: 32, }, }); export default App;Step 3: Run Project
In the last step run your project using the below command.
expo start
You can QR code scan in Expo Go Application on mobile.
Output:It will help you...