Home > other >  React Native - change color based on api value
React Native - change color based on api value

Time:08-10

i'm making a React Native project, and basically, i wanted to change a styled component background color based on the value of the api, but no idea how i'll make this

(i'm using: React Native, Expo, typescript and styled components)

i wanted the ContainerRating (which is a styled component) background turn to green if levelRiskMorse in API is equal to "NoRisk"

This is the api server.json:

 "allTasks": [
        {          
            "patientName": "PacientOne",
            "taskName": "Walk",
            "executors": "Person3 - Doctor",
            "institutionName": "IntitutionName",
            "generalObservations": "Observations Test",
            "planType": "1588",
            "time": "07:00",
            "risk": true,
            "levelRiskMorse": "NoRisk",
            "levelRiskBarden": "Low"
        }, 

this is a fake API !

Component itself and the styles.ts:

[...]

const [risk, setRisk] = useState('');

//fetching data

    useEffect(() => {                            
        async function getRiskLevel(){
            const { data } = await api.get('allTasks');
            const response = data.forEach((item: any | undefined) => {
                return item.levelRiskMorse
            })
            setRisk(response);
        }
        getRiskLevel();
           
    }, [])


 return(
<View>
 <ContainerRating> // if levelRiskMorse === "NoRISK" color turn to green
    <Text>Sem Risco</Text>
    <Text>0-24</Text>
 </ContainerRating>                         
</View> 
               
    )
} 
export const ContainerRating = styled.View`
    border-width: 0.6px;
    border-color: ${({theme}) => theme.colors.default_color};
    flex-direction: row; 
    justify-content: space-around;                               
    height: 50px;
    align-items: center;
    margin-top: 2px;
    border-left: unset;
`;

sorry if i didn't make it clear, im not used to ask questions here

CodePudding user response:

Simple do something like:

<ContainerRating style={{color: levelRiskMorse==="NoRISK" ? 'green' : defaultColor }}
     <Text>Sem Risco</Text>
     <Text>0-24</Text>
</ContainerRating>

What's happening? I'm applying a style object directly in the component (every component has this property). levelRiskMorse==="NoRISK" it's an if condition inline. If it is true, 'green' will be set, otherwise a default color variable you want to use.

  • Related