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

What is the best way to keep an image centered in the nav-bar as it decreases in size?

As I work on building a website using a template (https://github.com/learning-zone/web-templates/tree/master/victory-school-free-html5-bootstrap-template), I encountered an issue with the navigation bar. The original design appears like this: Before shrin ...

What is the best way to retrieve the results of an indexedDb request beyond the limitations of its callback function?

I am working on a form that has an input box which I want to auto-complete with values from an IndexedDb objectStore. Currently, it is functioning with two overlapping input boxes, using a simple array. However, I am looking to make it work with the values ...

What is the purpose of using a tag within a Next.js Link component?

Exploring the wonders of NextJs, I can't help but question why the a tag is necessary when creating a link. In the tutorial provided, we see this example: <Link href="/"><a>Back to home</a></Link> However, the link s ...

What is the most efficient way to display a dynamic alphabetical order list?

sample code: <table width="100%" cellspacing="0" cellpadding="0" border="0" style="line-height: 1.7;"> <tbody> <?php $this->db->select('*'); $this->db->from('cm_options'); ...

Tips for Aligning an Image Just Above a Card in Mobile and Tablet Screens with Tailwind CSS

https://i.stack.imgur.com/tPXEQ.jpg https://i.stack.imgur.com/3XkJo.jpg Just a heads up, this code snippet performs well on desktop but may have some issues on mobile and tablet devices. If anyone in the StackOverflow Community can offer some assistance, ...

Check if a user is currently on the identical URL using PHP and JavaScript

In my Laravel and AngularJS project, I have a functionality where users can view and edit a report. I'm looking to add a feature that will prevent multiple users from editing the report at the same time - essentially locking it while one user is makin ...

Having difficulty with Axios due to the URL containing a potent # symbol

When I pass a URL in axios, such as: https://jsonplaceholder.typicode.com/todos/#abc?pt=1 I only seem to receive the base URL in my network requests: https://jsonplaceholder.typicode.com/todos/ If anyone has insight on correctly passing URLs with #, yo ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Customizing Styles in Material UI with React

I am facing an issue with customizing the styles in my Material UI theme in React. Specifically, I am trying to modify the border of the columnsContainer but it doesn't seem to work, only the root style is having an effect. Take a look at this Codesa ...

Navigating a parameter within an AngularJS directive

I am currently developing a directive that acts as a wrapper for the freebase search widget using jQuery. This is my first attempt at creating a directive and I have encountered some challenges. Here are the functionalities I am aiming for: 1. The ability ...

What is the most effective method for importing .module.scss classes in a React project?

In the midst of my NextJs project, I have encountered two different methods for importing CSS classes from a .module.scss file. Method 1: import * as styles from './page.module.scss'; Classes are used like this: <div className={styles.myCla ...

Issue with primeng dropdown not displaying the selected label

When using the editable dropdown with filter feature from PrimeFaces, I've noticed that selecting an option displays the value instead of the label. Here is the code snippet: <div class="col-md-5 col-xs-12"> <p-dropdown [op ...

Clone all documents from a NodeJS mongoose collection and transfer them to a different server's database

I need assistance with migrating my database to a new server. My collection consists of approximately 410,000 documents, and I am looking to transfer them in batches of 100 to my new server that runs on mongodb. Below is the code I have written for this ...

Could someone confirm if this NextJS scss module is functioning correctly, or is there an issue on my end

Within my project, I am utilizing a pagination.tsx component in conjunction with a pagination.module.scss file which houses the following styles: .pagination { ul { display: inline-block; padding-left: 0; margin: 20px 0; border-radius: 4p ...

Creating a collection by gathering data from interactive fields with the help of AngularJS

I have a project to create an attendance system for employees. The system requires me to track the attendance status of each employee by generating a dynamic form with text input fields and checkboxes using angularjs ng-repeat inside a table. This form wil ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

Positioning of buttons within a div

I am currently designing an inspiration post style: https://i.stack.imgur.com/I5J0H.png However, I am encountering some challenges while creating it: The buttons are not rounded when the window size is changed Social icons are not being displayed I am ...

Experiencing an endless loop while sending a request to an endpoint within my component and utilizing the useState hook

Just starting out with react. Currently, I'm attempting to make a web request to an endpoint but the response seems to be stuck in an endless loop. import "./styles.css"; import instance from "./instance"; import { useEffect, useSt ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...