Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature.

The technologies I am using for this project include React Native, Expo, TypeScript, and styled components.

My goal is to have the background color of the ContainerRating component (which is a styled component) turn green if the levelRiskMorse value in the API response is equal to "NoRisk".

Here is a snippet of the server.json API:

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

This API shown here is just for demonstration purposes!

Below are the relevant code snippets of the component itself and its corresponding styles:

[...]

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> // Change color to green if levelRiskMorse === "NoRISK"
    <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;
`;

Apologies if my question was not very clear, I'm still getting used to asking questions in this format.

Answer №1

To achieve this effect, you can simply do the following:

<StyledRatingContainer style={{color: riskLevel==="NoRISK" ? 'green' : customColor }}
     <Text>No Risk</Text>
     <Text>0-24</Text>
</StyledRatingContainer>

What's going on here? I am directly applying a style object to the component (each component includes this property). The condition riskLevel==="NoRISK" is an inline if statement. If it evaluates to true, the color will be set to 'green', otherwise it will default to a custom color of your choice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enable divs to be interactively chosen

I have created two selectable divs that function like buttons. By using the left and right arrow keys, I am able to select one of the divs with this code: document.addEventListener("keydown", keyDownDocument, false); function keyDownDocument(e) { var k ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

Can you guide me on implementing an onclick event using HTML, CSS, and JavaScript?

I am looking for a way to change the CSS codes of the blog1popup class when the image is clicked. I already know how to do this using hover, but I need help making it happen on click instead. The element I want to use as the button; <div class=&quo ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

Encountering a Prettier error with React Native 0.71 and Typescript

https://i.stack.imgur.com/h9v5X.pngThe app runs smoothly, but these red warnings are really bothering me. How can I resolve this issue?https://i.stack.imgur.com/NebzJ.png ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Modifying the functionality of "use-input" in Vue.js

Currently, I am utilizing vue.js along with typescript to create an input field that allows users to either choose items from a drop-down menu or manually type in their own input. There are various scenarios where custom input might be allowed or where onl ...

Tips for developing a dynamic game that adjusts to different screen sizes using Phaser 3

Recently, I've been on the hunt for a way to ensure my game adapts seamlessly to various screen resolutions when using Phaser 3. In the past, I achieved this with ease in Construct 2. However, I'm now curious to explore how best to implement thi ...

React is a powerful tool that allows for the dynamic changing of state within

Struggling with my first React app and trying to accomplish something basic. The Input component in my app has an array in state, which sends two numbers and a unique ID as an object to a parent Component when the array has two numbers entered. Sending t ...

Retrieve progress with easing using jQuery's animate() function

At the moment, I'm utilizing this code to create an animation for a bar-graph-inspired element: $('.anim').animate({ right: `${100-(e/max*100)}%`, backgroundColor: colors[0] },{ duration: 1500, easing: 'easeInQuart&apos ...

React Router isn't displaying any content

I'm facing an issue with react-router-dom where none of my components are rendering and I just see a blank white screen. The content is not being added to my index.html template, even though there are no visible errors. Interestingly, it mentions that ...

Retrieve the HTML value of an element in Vue.js by clicking on its adjacent element

Hey there, I'm currently working on a simple notes app and I've hit a roadblock with one particular feature. In my project, I have a card element with a delete button as a child. What I need to achieve is to check if the value of the .card-title ...

Tips for creating image hover effects on jcarousel

I have successfully implemented Jcarousel from and it's functioning perfectly. Is there a way to create a rollover effect for the images when hovering over them with the mouse? What JavaScript code should be used for this, and where should it be impl ...

Struggling with sending mail using javascript and ajax?

Having trouble sending emails through my website using AJAX. It seems like the data is not being utilized or sent properly. I managed to get it working some time ago, but haven't checked on it since and now it has stopped functioning for some unknown ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate. After that, I configured my Vuex store.js file in the following way: import Vue from 'vue' import Vuex from 'vuex' import ...

Is it necessary to validate input for a login form? Some may argue that it creates unnecessary overhead and introduces concerns about an excess of javascript

While working on input validation for my registration form, the idea of implementing it on my login form also crossed my mind. My login form only requires an email and password. I'm considering validating whether the email entered is a valid email add ...

Mac users may experience lag when using Javascript parallax effects

I created a parallax page where the background image changes using JavaScript translateY(- ... px)' similar to what you see on the firewatch website. On Windows, the parallax effect works smoothly. However, on macOS it is smooth only in Safari. All ...