javascriptreactjsreact-nativenon-repetitive

Assigning colors to data


Is there a productive way to assign a color to an element by considering the value passed, without repeating the code to every component?

For example I have this:

This is my code, but I have to add the switch statement to all my components and it seems cluttered, especially with a lot more colors to add.

const list1 = [
    {
      title: 'One',
      temperature: 'very high',
    },
    {
      title: 'Two',
      temperature: 'high',
    },
    {
      title: 'Three',
      temperature: 'medium',
    },
    {
      title: 'Four',
      temperature: 'low',
    },
    {
      title: 'Five',
      temperature: 'very low',
    },
];

export default class Regional extends Component {
    constructor(props) {
        super(props);
        this.state ={
            dataSource: list1
        }
    }

  render() {
        const { dataSource } = this.state;

        const showData = dataSource.map((l, i) => {
            let myColor = 'blue';

            switch (l.temperature) {
                case 'high':
                    myColor = 'red';
                    break;
                case 'medium':
                    myColor = 'yellow';
                    break;
                case 'low':
                    myColor = 'green';
                    break;  
                default:
                    myColor = 'grey';
            }
            return(
            <View style={{flex: 1, flexDirection: 'column'}} key={i}>
                <Text style={{flex: 1, color:myColor}}>{l.temperature}</Text>
            </View>
            )
        })

        return (
            <View>
                {showData}
            </View>
        )
  }
}

This works fine, but I have this in a lot of components.

If this is the best solution without getting complicated than I am happy with it, as it is just repetition and extra lines.

Any advice is appreciated. Thanks!


Solution

  • You could have an object colors where the keys are the different temperatures and the values are the colors. If the temperature isn't a property on the object, you can fallback to 'grey'.

    const colors = {
      high: "red",
      medium: "yellow",
      low: "green"
    };
    
    class Regional extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          dataSource: list1
        };
      }
    
      render() {
        const { dataSource } = this.state;
    
        const showData = dataSource.map((l, i) => {
          let myColor = colors[l.temperature] || "grey";
    
          return (
            <View style={{ flex: 1, flexDirection: "column" }} key={i}>
              <Text style={{ flex: 1, color: myColor }}>{l.temperature}</Text>
            </View>
          );
        });
    
        return <View>{showData}</View>;
      }
    }