Hey there, I'm completely new to React-Native and just started playing around with it. I encountered an issue where I needed a button to change its color dynamically between "green" and "red" based on a boolean value from a database.
Currently, I am using Google's "Firebase" as my main database.
Here is the initial code I have been working on:
import {StatusBar} from 'expo-status-bar';
import React, {Component} from 'react';
import {StyleSheet, Text, View, Pressable, TouchableOpacity} from 'react-native';
import {initializeApp} from 'firebase/app';
import {getDatabase, ref, onValue, set} from 'firebase/database';
import {color} from 'react-native-reanimated';
const firebaseConfig = {};
initializeApp(firebaseConfig);
export default class App extends Component {
constructor() {
super();
this.state = {
l1: this.readVals('l1/'),
};
}
readVals(path) {
const db = getDatabase();
const reference = ref(db, path);
onValue(reference, (snapshot) => {
const value = snapshot.val().obj;
return value;
});
}
setVals(path) {
const db = getDatabase();
const reference = ref(db, path);
const val = this.state.l1;
set(reference, {
obj: !val
});
this.state.l1 = !val;
}
render() {
return (
<View style={styles.container}>
<Pressable
style={({pressed}) => [
{
backgroundColor: this.state.l1 ? '#FF0000' : '#00FF00',
},
styles.button,
]} onPress={() => {this.setVals('l1/')}}>
<Text style={styles.buttonText}>Button</Text>
</Pressable>
<StatusBar style="auto" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FF0000',
alignItems: 'center',
justifyContent: 'center',
},
getButton: {
borderWidth: 1,
borderColor: 'rgba(0,0,0,0.5)',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderWidth: 2,
borderRadius: 7,
marginTop: 20,
width: 100,
height: 50,
backgroundColor: '#00FF00',
},
button: {
flex: 0.15,
borderWidth: 1,
borderColor: 'rgba(0,0,0,0.25)',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderWidth: 2,
borderRadius: 10,
marginTop: 20,
width: 200,
height: 100,
// backgroundColor: '#E84C3D'
},
buttonText: {
fontWeight: 'bold',
fontSize: 20,
},
});
When I click the button, the color changes correctly. Is there a way to make the color change based on the database value?
For instance, I would like the button to be initially 'green' if the value at 'l1/' location in "firebase" is true
, and 'red' if the value is false
.
Is this feasible?
Any guidance on implementing this would be greatly appreciated.
Thank you.
P.S. Please keep in mind that I am very new to React-Native(Sorry).