What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I have attempted to use both references and states to resolve this problem, but so far, the code continues to function in the same manner. Any assistance on this matter would be greatly appreciated. Thank you.

function CommentMargin({level}) {


const [marginColorState, setMarginColorState] = useState(colors.lightPurple);
const marginColor = useRef(null);

useEffect(() =>
    {   
        switch (level) {
            case 1:
                
                setMarginColorState(colors.lightPurple);
                marginColor.current(marginColorState);
        
            case 2:
                
                setMarginColorState(colors.crimson);
                marginColor.current(marginColorState);

            case 3:
                
                setMarginColorState(colors.orange);
                marginColor.current(marginColorState);

            case 4:
                
                setMarginColorState(colors.yellow);
                marginColor.current(marginColorState);

        }



    }


)


return (
    <View style={styles(marginColor).container}>

    </View>
);

}

export default CommentMargin;
const styles = (marginColor) => StyleSheet.create({
    container:{
        backgroundColor: marginColor.current,
        }

Answer №1

To simplify the component, it's best to remove the state, useEffect, and ref.

Instead of complicating things, set the background color based on the value of level using a regular function like this:

const getBackgroundColor = () =>{
        switch (level) {
          case 1:
            return colors.lightPurple
          case 2:
            return colors.crimson
          case 3:
           return colors.orange
          case 4:
            return colors.yellow
      }
}

const styles = () => StyleSheet.create({
    container:{
        backgroundColor: getBackgroundColor(),
}

Answer №2

When utilizing the second parameter of useEffect, you have the ability to specify when it should execute (typically, it runs on every update by default). Based on your code, it seems that passing level as the second argument is what you intend to do so that useEffect only triggers when level changes.

To implement useEffect with a second argument, follow this format:

         useEffect(() => {
              console.log(state); 
              //state value is accessed here and therefore needs to be included as a dependency
         }, [state])

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

The hamburger menu is malfunctioning and spilling over

// App.js import './App.css'; function App() { return ( <div className='navbar'> <label className="hamburger-menu"> <input type="checkbox" /> </label> <div class ...

I'm curious to know how this code is extracting parameters from the website URL. Can someone walk me through the process step by step?

I needed to extract parameters from a URL and started searching online for solutions. I came across a helpful link that provided the information I was looking for: After visiting the website, I found this code snippet: function getUrlVars() { var var ...

Can HTML5 be used to store IDs in PHP chat applications?

I'm in the process of developing a chat application with PHP. Everything is functioning properly, but I have encountered a potential loophole. I am implementing AJAX to fetch chat data as the user scrolls, similar to platforms like Facebook and Twitte ...

Connect the mileage tracker to a Datalist or grid view component

I recently downloaded the Odometer Sample from , however, I am facing an issue where only the first element in the Datalist is getting the Odometer display, while others are not displaying it. Here is the snippet of code: <script type="text/javascript" ...

Enhance your website with the jQuery autocomplete feature, complete with

Is there a way to incorporate smaller text descriptions alongside the search results displayed on my website? The descriptions are available in the data array used by autocomplete and can be accessed using the .result function by calling item.description. ...

What is the reason for the delay in the firing of this document.ready event

Similar Question: Understanding window.onload vs document.ready in jQuery I seem to be encountering a problem: I have an image on my webpage that is relatively small. I also have a JavaScript function that dynamically sets the height of the left sideb ...

Conceal/Inactivate element when scrolling, and once scrolling comes to a halt, reveal it once more

I have been working on creating a div tag to overlay an embed tag and added some javascript to prevent users from right-clicking to download the pdf inside the embed tag (even though it may seem unnecessary, it was requested by my customer). Here is the ma ...

Creating a sticky positioning effect in CSS

Can someone assist me in implementing the position: sticky as demonstrated below? Currently, the upcoming date overlaps the current date. This causes the opacity and shadow of the date to reach 100%, which can create a cluttered appearance if there are m ...

Do we need to have the 'input type file' field as

I am currently working on a PHP form that includes mandatory fields for saving the data. For example: <td><input class="text_area required" type="text" name="new field" This form also has Javascript code with file upload functionality, which I ...

Is it possible to perform a GET request between a site using HTTPS and another using HTTP?

https://i.stack.imgur.com/AlWYJ.png I recently hosted my site on Shopify using HTTPS, and then I attempted to make a GET request via Angular to a site that uses HTTP. Angular <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.j ...

Spring Security for client-side authentication utilizing cookies

We have successfully implemented a back-end login POST service using Spring Security, Spring Boot, and Spring Session. Users must be logged in to access other services, and the mechanism to restrict or allow access works seamlessly. Postman has been used f ...

Is it possible to load Javascript using AJAX with jQuery?

So I have this JavaScript code that I insert into a webpage using the following: <script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/sm13154955?w=640&h=395"></script> It basically places an object/embed code into the w ...

Testing the capabilities of AngularJS with e2e testing using the angular-recaptcha library

I have been attempting to e2e test my basic application, but I am facing challenges with the angular-recaptcha plugin from VividCortex (https://github.com/VividCortex/angular-recaptcha). Here is the test case I am working on: it('should redirect t ...

How can you adjust the width of the Material UI Select component?

Trying to customize the width of the Material UI Select component can be a bit tricky. To set the desired width, you need to assign a specific class to the FormControl component. This class, such as mw-120, should define the minimum width as 120px in your ...

Using JavaScript, what is the process for getting the value of a child node within Firebase

var ref = firebase.database().ref("games/" + gameId + "/patterns"); ref.on("child_changed", function(snapshot){ var pattern = snapshot.key; console.log(pattern); }); Currently, the code snippet above only logs the key. But how can I extract the player ...

Ensure that the HTML input only accepts numbers and email addresses

Is there a way to restrict an HTML input field to only accept numbers and email IDs? <input id="input" type="text" /> ...

My navigation menu has a nested ul, but on mobile devices, it doesn't display all the items in the list. What could be causing

When I click on "Products" in my main navigation, only the first 6 items are displayed from a nested ul. How can I make all of them display when the user clicks on "Products"? Is this a CSS issue or a problem with the script? Here's a screenshot for r ...

Tips for incorporating a personalized touch to your radio buttons

Is there a way to customize the appearance of radio buttons in React or HTML elements, such as the screenshot below? I want to maintain the display of the number No.01 followed by the label next to it. If you have any suggestions or solutions, please shar ...

Is there a way to logout when the select event occurs using the key?

I am trying to figure out how to log out the key value when the select event is triggered. Specifically, I want to access the key={localState.id} within the <select></select> element in my HTML. This key value is crucial for a conditional stat ...

What steps should be taken to guarantee that a reactjs state is successfully updated before triggering a function?

As I attempt to utilize reactjs to update a state, and afterwards trigger an ajax call to request a new page, I encounter an issue where the value of this.state.page is not updated after clickNextPage() is executed. Just prior to firing the ajax call, an o ...