This tutorial is very simple but interesting for beginners who wish to Dynamically Generate Random Color on button onPress in react native android and iOS application example tutorial in RGB color format by calling a function. So let’s get started .
Contents in this project Dynamically Generate Random Color on Button Click :
1. Import StyleSheet, View and Button component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Button } from ‘react-native’;
|
2. Create constructor() in your project. Now make a State named as ColorHolder in constructor() and define the default color in HEX color code. You can also define color code in RGB format. This state is used to set the default View background color.
1
2
3
4
5
6
7
8
9
10
|
constructor(){
super();
this.state={
ColorHolder : ‘#00BCD4’
}
}
|
3. Create a function named as ChangeColorFunction(). Now we would use the Math.floor and Math.random() function for generate random color and store the generated color into a Var . Now we would set that Var into ColorHolder State.
1
2
3
4
5
6
7
8
9
10
11
|
ChangeColorFunction=()=>
{
var ColorCode = ‘rgb(‘ + (Math.floor(Math.random() * 256)) + ‘,’ + (Math.floor(Math.random() * 256)) + ‘,’ + (Math.floor(Math.random() * 256)) + ‘)’;
this.setState({
ColorHolder : ColorCode
})
}
|
4. Create a View and Button inside render’s return block. Now we would call both Style Class and set backgroundColor using ColorHolder State. After that we would call ChangeColorFunction() on Button onPress event.
1
2
3
4
5
6
7
8
9
10
11
|
render() {
return (
<View style={[styles.MainContainer, { backgroundColor: this.state.ColorHolder }]} >
<Button title=“Change View Background Color” onPress={this.ChangeColorFunction} />
</View>
);
}
|
5. Create CSS Style Class.
1
2
3
4
5
6
7
8
9
|
const styles = StyleSheet.create(
{
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
}
});
|
6. Complete source code for App.js File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Button } from ‘react-native’;
export default class MyProject extends Component {
constructor(){
super();
this.state={
ColorHolder : ‘#00BCD4’
}
}
ChangeColorFunction=()=>
{
var ColorCode = ‘rgb(‘ + (Math.floor(Math.random() * 256)) + ‘,’ + (Math.floor(Math.random() * 256)) + ‘,’ + (Math.floor(Math.random() * 256)) + ‘)’;
this.setState({
ColorHolder : ColorCode
})
}
render() {
return (
<View style={[styles.MainContainer, { backgroundColor: this.state.ColorHolder }]} >
<Button title=“Change View Background Color” onPress={this.ChangeColorFunction} />
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
}
});
|
Screenshot in Android device: