Home > database >  In React Native, is there a way to change the color of the button based on a boolean from a database
In React Native, is there a way to change the color of the button based on a boolean from a database

Time:12-01

So, I'm a literal newbie to React-Native and I just started experimenting out stuff. So, I ran across this issue of having the color of button either "green" or "red" based on the boolean value present on a database.

So, at this point, I'm using Google's "Firebase" as my primary database.
This is the base code which I'm trying to work out.

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 press the button, the color changes as expected. But is there a way to change the color based on the value present in the database?

For example, in this case, I want the button to have the color 'green' from the moment the app is loaded up, if the value at location 'l1/'(in my example) in "firebase" has the value set to true, and similarly, I want the color to stay 'red' if the value at 'l1/' is false.

Can this be implemented?
If yes, any help received is very helpful to me.
Thank you.

P.S. Also, please note the fact that I'm very new to the field of React-Native(Sorry).

CodePudding user response:

for reRender screen you have to use state and when it's changed your Screen render again . and seems you used that . but you can try another way like that . at fist call to get your data in componentDidMount like this:

  componentDidMount() {
    console.log("componentDidMount");
     this.setState({  l1: this.readVals('l1/') });
  }

if l1 changed , it's should to be work for you .

CodePudding user response:

As you are working on class base component you can call an firebase function in a componentWillMount and get the color and save it to your state.

componentWillMount run before rendering so once you get the data you can setState and then by that state you can change the color of the button.

TRY THIS

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/'),
    };
  }

  componentWillMount() {
    const value = this.readVals('l1/');
    this.setState({l1: value});
  }

  readVals(path) {
    const db = getDatabase();
    const reference = ref(db, path);
    onValue(reference, (snapshot) => {
      const value = snapshot.val().obj;
      return value;
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <Pressable
          style={({pressed}) => [
            {
              backgroundColor: this.state.l1 ? '#FF0000' : '#00FF00',
            },
            styles.button,
          ]}>
          <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,
  },
});
  • Related