This is my very simple code:
import React from 'react';
import { Pressable, SafeAreaView, StyleSheet, Text, View } from 'react-native';
function generateRandomNumber() {
const min = 1;
const max = 100;
const randomNumber =
Math.floor(Math.random() * (max - min + 1)) + min;
return randomNumber;
};
function NoIdeaHowToFixScreen({ navigation }) {
let x = 1;
const pressRandom = () => [
x = generateRandomNumber(),
console.log(x),
]
return (
<SafeAreaView style={styles.container}>
<View>
<Text style={styles.letter_text}>x</Text>
</View>
<Pressable
style={{ backgroundColor: x < 50 ? "red": "green" }}
>
<Text style={{ color: "black" }}>{x}</Text>
</Pressable>
<Pressable
style={{backgroundColor: "black"}}
onPress={pressRandom}
>
<Text style={{ color: "white"}}>{"Random"}</Text>
</Pressable>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
})
export default NoIdeaHowToFixScreen;
I press one button to generate a random number (x) between 0 and 100. I want text label to display this number (instead of showing "x"). I also want another button to show updated random number and I want it to change its color.
I have no idea how to make it ðŸ˜
2
Answers
I haven’t used react in a while so maybe there’s something in react that can do this another way. But in straight JavaScript, you can do something like in this snippet.
In your case it might actually be better performance-wise to set the color directly via a style attribute. But the performance savings from doing this are minimal, and using classes lets you use CSS the way it is meant to be used (ie for styling)
You should handle state change by use useState