The JavaScript inbuilt function Math.floor() and Math.random() function is used in this tutorial. The Math.floor() function is used to round the given number to its downward integer value. The Math.random() function is used to Generate Random Number to any range in Point Float value. So we would use both Math.floor() and Math.random() function together to generate random number between given range. User can himself define the range like i did in this tutorial and the number will only be generated between given range.
Contents in this project Generate Random Number Between 1 to 100 in React Native :
1. Import StyleSheet, View, Button and Text component.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Button, Text } from ‘react-native’;
|
2. Create constructor() in your project. Now we would make a State named as NumberHolder.
1
2
3
4
5
6
7
8
9
10
11
|
constructor(){
super();
this.state={
// This is our Default number value
NumberHolder : 1
}
}
|
3. Create a function named as GenerateRandomNumber() . Inside this function we would Generate Random Number using Math.floor() and Math.random() function and store the generated number into NumberHolder State.
1
2
3
4
5
6
7
8
9
10
11
|
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 100) + 1 ;
this.setState({
NumberHolder : RandomNumber
})
}
|
4. Create a Root View, Text and Button component in render’s return block. The Text component is used to show the Random number.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
render() {
return (
<View style={styles.MainContainer} >
<Text style={{marginBottom: 10, fontSize: 20}}>{this.state.NumberHolder}</Text>
<Button title=“Generate Random Number” onPress={this.GenerateRandomNumber} />
</View>
);
}
|
5. Create the Style :
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
52
53
54
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Button, Text } from ‘react-native’;
export default class MyProject extends Component {
constructor(){
super();
this.state={
// This is our Default number value
NumberHolder : 1
}
}
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 100) + 1 ;
this.setState({
NumberHolder : RandomNumber
})
}
render() {
return (
<View style={styles.MainContainer} >
<Text style={{marginBottom: 10, fontSize: 20}}>{this.state.NumberHolder}</Text>
<Button title=“Generate Random Number” onPress={this.GenerateRandomNumber} />
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
}
});
|
Screenshot in Android device:
Screenshot in iOS application :