What is the best way to apply the background color from the bgColour variable to the component styled with the card class?

I am trying to set the variable bgColour inside an if statement to match the background colour of a div with the class of card. However, my attempts to access it have been unsuccessful. Can someone provide guidance on how to resolve this issue? Additionally, if there is a way to achieve this using a separate CSS file, that would be ideal.

renderIssues2 = () => {
    let bgColours = ['Green', 'Yellow', 'Red'];
    let statusOptions = ['Available', 'Under Maintenance', 'Not Working'];
    return this.state.issues.length > 0 ?
        this.state.issues.map((issue, index) => {
            for (let i = 0; i < statusOptions.length; i++) {
                if (statusOptions[i] === issue.status) {
                    let bgColour = bgColours[i];
                }
            }
            return (
                    <div class="card" >
                        <div class="card-title">{issue.issues}</div>
                        <div class="card-body">{issue.message}</div>
                    </div>
            );
        })
        :
        null;
}

Answer №1

  • It is unnecessary to use the forLoop to determine the bgColour
  • The bgColour variable is block scoped inside the forLoop

const { issues } = this.state;
let bgColours = ["Green", "Yellow", "Red"];
let statusOptions = ["Available", "Under Maintenance", "Not Working"];
return issues.length > 0
  ? issues.map((issue, index) => {
      const colorPos = statusOptions.indexOf(issue.status);
      const bgColor = bgColours[colorPos];
      const style = bgColor ? {"backgroundColor": bgColor} : {};
      return (
        <div class="card" style={style}>
          <div class="card-title">{issue.issues}</div>
          <div class="card-body">{issue.message}</div>
        </div>
      );
    })
  : null;
};

Answer №2

You can also establish a connection between status and color by creating an Object

const statusToColor = {
  'Available': 'green',
  'Under Maintenance': 'yellow',
  'Not Working': 'red',
};

displayIssues2 = () => {
  return this.state.issues.length > 0
    ? this.state.issues.map((issue, index) => {
        const bgColor = statusToColor[issue.status];
        return (
          <div class="card" style={{ backgroundColor: bgColor }}>
            <div class="card-title">{issue.issues}</div>
            <div class="card-body">{issue.message}</div>
          </div>
        );
      })
    : null;
};

Answer №3

It seems like you've defined the variable bgColour to hold a color value from your bgColours array, but you're not utilizing that variable in rendering your card, so that color isn't being applied anywhere.

Include the bgColour as a class in your card element, and then define classes for each of your colors in a CSS file, perhaps your main index.css.

<div className={"card " + bgColour}>
   <div className="card-title">{issue.issues}</div>
   <div className="card-body">{issue.message}</div>
</div>
.Green{
   background-color: green;
}
.Yellow{
   background-color: yellow;
}
.Red{
   background-color: red;
}

Additionally, in React, make sure to use className instead of class when assigning class names. Styling Docs

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

Differences in wrapping between IE11 and Chrome/Firefox: <DIV>

Take a look at this jsfiddle link using IE 11, Chrome, and FireFox. Here is the HTML code I am working with: <div style="width:120px;background-color:#EE1111;"> <div class="daytext"><b>27</b></div> <div class="dayitem"> ...

Tips for confirming the successful loading of the reCAPTCHA JS file prior to form submission

My issue involves a recaptcha and a registration form. Let me share with you a simplified version of a handler: //my_script.js document.getElementById("my_form").onsubmit = function(e) { e.preventDefault(); grecaptcha.execute(); var grecap_resp = g ...

Display a React Material-UI Button variant depending on the isActive state of a NavLink using TypeScript with Material-UI and React Router v

I'm attempting to dynamically change the variant of a mui Button based on the isActive state of a Navlink, but I'm running into an error <Button to="/" component={NavLink} variant={({isActive}:{isActive:any}) => isActive ? 'contained&a ...

Append X lines to the conclusion of the paragraph while simultaneously deleting an equal number of lines from the beginning

I am working with a large string that is displayed in a text area. The string is divided into lines using \n, and new lines are continuously added as the program executes. In order to prevent the program from slowing down or causing the browser to cr ...

What is the proper way to specify the background image path in CSS?

My CSS file is located at: Project/Web/Support/Styles/file.css The image I want to use is found here: Project/Web/images/image.png I am attempting to include this image in my CSS file. I have tried the following methods: 1) background-image: url(/images ...

Switch the toggle to activate or deactivate links

My attempt at coding a switch to disable and enable links using CSS is functional in terms of JavaScript, but the appearance is not changing. I am lacking experience in this area. Here is my HTML Button code: <label class="switch" isValue="0"> ...

Unable to add padding to <b> tag

Can anyone explain why the padding-top property is not taking effect for the <b> tag? Check out this link <b>hello world</b>​ b { padding-top: 100px; } ​ ...

The smallest allowable page height is equal to the height of the viewport

I am facing a seemingly simple problem that is causing me quite a bit of confusion. For instance, in the code snippet provided, the header should have a height of 130px and the footer should be 20px tall. I require a certain min-width for my #landing-page ...

Is C# code allowed in a CSS file for ASP.NET MVC 5?

Looking for the best approach to define a set of colors in one place and utilize functions to create different shades of these colors, then incorporate them into CSS files. Transitioning from Ruby on Rails to ASP.NET has prompted me to seek alternatives. ...

I am looking to switch the input border-bottom color to blue when the input field is focused or has valid content

Can someone help me change the border bottom color of my input to blue in the following HTML code: .inputBox input:focus ~ input, .inputBox input:valid ~ input{ border-bottom: 1px solid #0000cd; } <div class="i ...

Encountering: Server Failure TypeError: Unable to access attributes of an undefined element (accessing 'length') within NextJS

Why is the component rendering correctly but the browser console is throwing an error? How can I resolve this issue? in firebase.js import * as firebase from "firebase/app"; const firebaseConfig = { apiKey: "my api code", authDomain: "mywebs ...

What is the best way to position a bigger character directly above a smaller container?

My goal is to center a single character, using CSS, in a span that is smaller than the character itself. The setup I have is: <span id="A">X</span><span id="B">Y</span><span id="C">Z</span> All three spans are styled ...

Guide to making a prop optional in reactjs with the help of typescript

Issue: I have a parent component and reusable component. The reusable component is used twice within the parent component. When passing a boolean prop named 'visible' to one of the instances of the reusable component, PyCharm throws an error stat ...

The functionality of Bootstrap's Inline Block feature appears to be malfunctioning

Make sure to visit this awesome website: Upon visiting the site, you'll notice the top menu with 3 options (My Account, Need Help & Cart). However, it seems that the Cart option is not aligning properly with the others. I attempted to use display: i ...

Django is looking for a primary key that I do not possess

Encountering an issue: invalid literal for int() with base 10: 'ljrh' This error occurs when attempting to add a new entry in a model: day = itemize(value, getday(strip(key))) add = Reoccurring(request.user.username, strip(day.Day), strip(day. ...

I don't understand why my BeautifulSoup code is throwing an attribute error even though the variable it's referring to is assigned a value

Currently, I am working with Python 3.9.1 along with selenium and BeautifulSoup to develop my first web scraper targeting Tesco's website. This is essentially a mini project that serves the purpose of helping me learn. However, upon running the code p ...

Is there a way to adjust the position of ::before elements without affecting the border placement?

I'm struggling with an element that has a CSS style ::before to display an arrow-up inside a black circle. Check out the code here The issue I'm facing is that the character \25b2 isn't centered vertically within the circle. Adjustin ...

Hyperlinks are being loaded

I recently noticed that my website was loading very slowly because I had quoted Wikipedia and included a direct link to the article. The link code looked like this: <a href="<?php echo $data['link']; ?>" target="_blank"><?php echo ...

Facing problems with Next.js useRouter in version ^14.0.4

When I import useRouter from "next/navigation" in a Higher Order Component (HOC), it results in the following error: Error: node_modules/next/dist/client/components/app-router.js ReferenceError: location is not defined The HOC is being used by ...

Animating HTML elements with JavaScript and CSS when hovering the mouse

Recently, I stumbled upon the SkyZone website and was impressed by the captivating JavaScript/CSS/HTML effects they used. I was inspired to include similar effects on my own website. (Visit the Home Page) One noteworthy feature on their website is the n ...