MonsterMackan
MonsterMackan

Reputation: 21

How do i do multiple checks on a props value in order to change the color of that value. Inside of style={ }?

I am trying to build an app that lists tasks to be completed. In those task there is a priority number 1-5. I have implemented a solution to change the color of that number from green to yellow if the value of the number goes over 2. But i also want the number to change to the color red if it has the value of exactly 5. How can this be done?

Below is the code for the PrioLvl component which is where this feature should take place.

import { View, Text, Image, ScrollView, TextInput, StyleSheet } from 'react-native';

class PrioLvl extends React.Component {
    constructor(props){
        super(props)
    }
    render(){
        return (
            <View style={styles.container}>
                <Text style={this.props.prio > 2 ? styles.yellow : styles.green}>{this.props.prio}</Text>
            </View>
        ) 
    }
}


const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        justifyContent: 'center',
        width: 100,
    },
    green:{
        fontSize: 50,
        color: '#5cb85c'
    },
    yellow:{
        fontSize: 50,
        color: '#f0ad4e'
    },
    red: {
        fontSize: 50,
        color: '#d9534f'
    }

    
});


export default PrioLvl;

Upvotes: 0

Views: 32

Answers (1)

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

You could factor the logic out into a helper method:

import { View, Text, Image, ScrollView, TextInput, StyleSheet } from 'react-native';

class PrioLvl extends React.Component {
    constructor(props){
        super(props)
    }

    getStyle = () => {
       if (this.props.prio === 5) return 'red'
       if (this.props.prio > 2) return 'yellow'
       return 'green' 
    }
    render(){
        const style = this.getStyle()
        return (
            <View style={styles.container}>
                <Text style={styles[style]}>{this.props.prio}</Text>
            </View>
        ) 
    }
}


const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        justifyContent: 'center',
        width: 100,
    },
    green:{
        fontSize: 50,
        color: '#5cb85c'
    },
    yellow:{
        fontSize: 50,
        color: '#f0ad4e'
    },
    red: {
        fontSize: 50,
        color: '#d9534f'
    }

    
});


export default PrioLvl;

Alternatively, you could chain multiple ternary operators together inside of the style={} attribute. But I think the above approach is easier to read.

Upvotes: 1

Related Questions