Search code examples
react-nativecss-modules

How to differentiate two different CSS props to be conditionally styled, that have the same name in React Native?


I have this style: <TouchableOpacity style={[styles.container, { backgroundColor }]}> and this switch case:

    let backgroundColor = "white";
    switch (this._getName()) {
        case "bot":
            backgroundColor = "#F6F9FC";
            break;
    }

That correctly change the background color of the TouchableOpacity component when the name is "bot".

Inside that TouchableOpacity, I have this: that correctly changes the color of a circle based on a certain state when mixed with these switch cases:

    const { report } = this.props;
    let backgroundColor = "gray";
    switch (report.status) {
        case "active":
            backgroundColor = "green";
            break;
        case "inQueueForMaintenance":
            backgroundColor = "yellow";
            break;
        case "inMaintenance":
            backgroundColor = "yellow";
            break;
        case "defeated":
            backgroundColor = "red";
            break;
    }

However, if I mix both switch cases, it'll conflict because both props are backgroundColor. How to avoid this?


Solution

  • Why don't you try the classic way of creating objects. Use two different names.

    let firstBg = "white";
    switch (this._getName()) {
        case "bot":
            firstBg = "#F6F9FC";
            break;
    }
    
    { backgroundColor: firstBg }
    

    and then,

    const { report } = this.props;
    let secondBg = "gray";
    switch (report.status) {
        case "active":
            secondBg = "green";
            break;
        case "inQueueForMaintenance":
            secondBg = "yellow";
            break;
        case "inMaintenance":
            secondBg = "yellow";
            break;
        case "defeated":
            secondBg = "red";
            break;
    }
    
    { backgroundColor: secondBg}