lundi 19 octobre 2020

How to change BackgroundColor depending of a value in react native

I'm trying to render some bars for some stats, and i want the color of them depending of the value they have. I tried using if statements and switch but it doesn't seem to work

for the switch it will use the default value and the if will use the first checked value.

Sry for my english 😅

import React from "react";
import { View, Text, StyleSheet } from "react-native";

const Stats = ({ statName, value }) => {
  let color;

  if (value == 0) {
    color = "";
  } else if ((value) => 1 && value < 25) {
    color = "red";
  } else if (value >= 25 && value < 50) {
    color = "orange";
  } else if (value >= 50 && value < 90) {
    color = "yellow";
  } else if (value >= 90) {
    color = "green";
  }

  //   switch (value) {
  //     case value >= 1:
  //       color = "red";
  //       break;
  //     case value >= 25:
  //       color = "orange";
  //       break;
  //     case value >= 50:
  //       color = "yellow";
  //       break;
  //     default:
  //       color = "";
  //   }

  return (
    <View style={styles.container}>
      <Text>{statName}</Text>
      <Text>{value}</Text>
      <View
        style={[styles.bar, { width: value * 1.5, backgroundColor: color }]}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  bar: {
    height: 20,
  },
});

export default Stats;

Aucun commentaire:

Enregistrer un commentaire