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

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

Troubleshooting JavaScript Oscilloscope: resolving audio playback problems

I am exploring JavaScript for the first time and came across an interesting oscilloscope example on this GitHub page. It seemed quite easy to follow initially, but I am facing an issue with audio playback. Although the HTML5 audio element loads the audio f ...

Connect the keys from one enum to either keys or values in another enum

When working with the code below, it is important that the keys of PropertiesNamesInDataBase align with those in User.Keys. While the values of PropertiesNamesInDataBase are used in the backend, it is crucial for uniformity that the names match in the fron ...

When implementing `useRouter().push()` in Next.js, it has the ability to refresh

I have recently started using a custom node server in my Next.js app. Previously, useRouter().push() was working fine without a custom server and providing a seamless single-page app experience. However, with the custom server, it now refreshes my applicat ...

Is there a way to replicate the ctrl-F5 function using jQuery?

Is there a way to use jQuery to refresh the page and clear the cache at the same time? ...

A helpful guide on passing a component as a prop to a child class and incorporating it within the child component along with additional props

Within my parent class, I have loaded a child class component and passed another component to it as a prop. In the childclass component, I am trying to display that component. <EditRecordModal show={this.state.showEditModal} onHide={this.handle ...

Expanding unfamiliar categories

Currently, I am working with Gutenberg blocks in a headless manner. Each Gutenberg block is defined by the following structure: type Block = { name: string; className?: string; key?: string | number; clientId: string; innerBlocks: Block ...

Tips for ensuring the security of your code in node.js

Here is a snippet from my app.js that deals with managing connections: var connections = []; function removeConnection(res) { var i = connections.indexOf(res); if (i !== -1) { connections.splice(i, 1); } } I make a call to removeConn ...

How can I implement the dynamic loading of components using the Vue 3 composition API?

My goal is to dynamically load a component with the name retrieved from the database, however, I keep encountering the error [Vue warn]: Component is missing template or render function. import SimpleQuestions from '@/components/SimpleQuestions.vue&ap ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

What is the process for assigning an element to a specific URL ID?

Imagine having an array of objects structured like this: [{ details: {id: 7}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: 8}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: ...

The AJAX request is not successful because it is encountering a ReferenceError due to attempting to assign a value to an

My attempt to trigger a modal using dynamic data from the database with an AJAX function is encountering issues. Upon clicking the button to open the modal, I encounter this error: ReferenceError: assignment to undeclared variable PostRPC in category.ph ...

What is the proper method for setting up handlers in functional React components?

My knowledge of JavaScript tells me that there are three different ways to define functions. Let's take a look at them: 1. Declaration function handleEvent(e) {} 2. Assignment var handleEvent = function(e) {} 3. Arrow var handleEvent = (e) => ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Transferring Cookies through FETCH API using a GET method from the client-side to the server-side

Struggling with a challenge here: Attempting to send a cookie via a GET request to determine if the user is logged in. The cookie is successfully transmitted to my browser and is visible in the developer tools. When I manually make a request through the UR ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Generating React components dynamically can bring flexibility and efficiency to the

Looking for a solution to dynamically render different components based on the arguments passed with data. While using regular or React.createElement(Item) works fine, all other options seem to fail. http://jsfiddle.net/zeen/fmhhtk5o/1/ var React = windo ...

Nunjucks not loading the script when moving from one page to another

Currently, I am in the process of developing a website utilizing nunjucks and express. This website serves as a blog platform with content sourced from prismic. My goal is to load a script file for an active campaign form whenever a user navigates from a b ...

What's the best way to organize a list while implementing List Rendering in VueJS?

Currently, I am working on List Rendering in Vue2. The list is rendering correctly, but it appears ordered based on the data arrangement in the array. For better organization, I need to sort each item alphabetically by title. However, I am facing difficult ...