Code Styling within Components of a React Application

I'm struggling with setting up inline CSS styles in my React App. I want to dynamically change the background color of my cards based on data in an array, but so far have been unsuccessful. I've created a variable with a switch statement and passed it as inline style, but the background color is not changing. Can anyone help me solve this issue or suggest another solution? Thank you.

Here is my Card.js:

import React , { Component } from 'react'

export default class Card extends Component {
    render(){
        const {title , date , description , color } = this.props.node
        let cardClass = "card-wrapper"
        let myColor = ""
        switch(color) {
             case 'red':
             myColor = 'color--red'
             break;
             case 'blue':
             myColor = 'color--blue'
             break;
             case 'yellow':
             myColor = 'color--yellow'
             break;
             case 'darkBlue':
             myColor = 'color--darkBlue'
             break;
             default:
             break;
            }

        return (
            <div style={{ backgroundColor: myColor }}>
                <div className={cardClass}>
                     <div className="card">
                        <h5 className="card-title">{title}</h5>
                        <p>Created on {date}</p>
                        <p className="card-text">{description}</p>
                  </div> 
              </div>
            </div>
        )
    }
}

This is my App.css file:

.card-wrapper {
  width: 209px;
  margin: .4%;
  float: left;
  background-color: #5cb85c;
  color: white;
  padding: 16px;
  border-radius: 1px;
}

.color--red {
  background-color: #d9534f;
}
.color--blue{
  background-color: #5bc0de;
}
.color--darkBlue{
 background-color:  #428bca;
}
.color--yellow {
  background-color: #FFD333;
}

And this is my data.js file:

export const data = [
     {
        title : 'title',
        date : '1537032686201',
        description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
        color:'red'
     },
     {
        title : 'title',
        date : '1537032686202',
        description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
        color:'blue'
     },
     {
        title : 'title',
        date : '1537032686203',
        description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
        color:'darkBlue'
     },
     {
        title : 'title',
        date : '1537032686204',
        description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
        color: 'yellow'
     },
]

Answer №1

It is recommended to utilize className in place of style:

return (
  <div className={myShade}>

Answer №2

The most recommended solution is to utilize the classnames npm package.

Simply execute:

npm install --save classnames

Visit: https://www.npmjs.com/package/classnames

Then, your revised code will appear as follows:

import React , { Component } from 'react';
import classnames from 'classnames';

export default class Card extends Component {
    render(){
        const {
          title,
          date,
          description,
          color
        } = this.props.node;

        return (
          <div
            className={classnames(
              'card-wrapper', {
                'color--red': color === 'red',
                'color--blue': color === 'blue',
                'color--yellow': color === 'yelow',
                'color--darkBlue': color === 'darkBlue',
              }
            )}
           >
             <div className="card">
                <h5 className="card-title">{title}</h5>
                <p>Created on {date}</p>
                <p className="card-text">{description}</p>
            </div> 
          </div>
        )
    }
}

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

Implementing the autoprefixer script into the project created with react-create-app

Currently, I'm facing a challenge in integrating an autoprefixer script from postcss into my project. The difficulty lies in the fact that my setup does not include webpack, grunt, or gulp. In my package.json, this is the configuration of my scripts: ...

Simple steps to incorporate the cube.js API into your JavaScript code

Does anyone know how to easily incorporate the cube.js API into basic JavaScript code? I'm looking to utilize the cube.js API on a simple HTML and JS page. I noticed in the cube.js documentation, they provide guidance for integrating it with React, V ...

Tips on customizing text input in jQuery editable

I have been tasked with customizing the Text Input within my Table using jQuery editable. You can access the Table here. When you navigate to the page and click on Wordpress Design, you are able to edit the text within the Text Input. However, the issue a ...

The top-center alignment in Toaster (ngx-toastr) is missing a top margin

I recently started using the ngx-toastr library in my project. I have a message service that displays error messages at the top-center of the screen with the following code: @Injectable() export class MessageService { constructor(private toastrServic ...

Evaluating the similarity between a Guild ID and a matching string

Currently, I am in the process of creating a bot with a unique feature - a config command that enables users to customize specific functionalities within their servers. This customization is facilitated through a straightforward JSON file named config.json ...

An effective way to mimic an un-exported (private) function within a user module using Jest

In my code, I have a function that handles API requests called "private" and several other functions that initiate specific requests with configuration objects. For example, in the requestUploadStatementFile file. I want to test these public functions, bu ...

"What is the best way to eliminate duplicate data from an ng-repeat loop in AngularJS

I have a query regarding appending data from the second table into $scope.notiData in AngularJS. Additionally, I need to figure out how to remove ng-repeat data when the user clicks on the remove symbol X. I have attempted some code but it is not functioni ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

Disabling other fields with Bootstrap DateTimePicker

I am interested in understanding how the Bootstrap DateTimePicker stores dates. I need to disable other text box fields on my webpage based on this information. I have set up a page with multiple GridViews for querying purposes and I want to prevent users ...

Update the value of a Vue tree select component using JavaScript

I'm working on a school project using plain JavaScript and needed a tree view select with multiple layers. After extensive searching, I stumbled upon this tool. It's working smoothly, but the one thing that has me stumped is how to change its va ...

jQuery allows us to set two separate conditions for two distinct variables

I've written this function: settings_rc_left.on('click', function(){ var settings_list_last_element_id_one = settings_menu_element.attr('id') == 'r_02', settings_list_last_element_id_two = settings_menu_eleme ...

Having difficulty arranging the elements in a straight line

I am currently working on designing the footer for my website. My goal is to have 2 divs and one list displayed inline within this footer. However, I am facing an issue where using the CSS Property display:inline-block is not achieving the desired result. ...

Using a forward slash in the path for the href attribute in a CSS link within an ejs file

Image 1: Configuring express.static for the public folder Image 2: Adding href="/app.css" in post.ejs file Image 3: Final result While experimenting with using /app.css and app.css in the post.ejs file, I noticed that the outcome was consistent with th ...

Please provide guidance on using NPM to install dependencies in this Visual Studio Code project. Let's

Currently learning React and exploring this repository. After cloning and running NPM install, a lengthy output is generated: (Note: Stackoverflow only allows max 30,000 characters, original output was 300,000) The majority of the output is highlighted i ...

Verify whether the selection has changed within the OnClick event

Take note: The answer marked as the solution addresses the issues presented in the Title. However, I was able to resolve my underlying issue with type ahead dropdowns by switching to IE8. I am looking to trigger a postback ("this.form.submit()") when a ne ...

Creating a connection between a secondary jQuery anything slider and a distinct CSS style on a webpage

Currently, I am attempting to incorporate two anything sliders within the same webpage. My goal is to apply unique styling to each slider. Despite my efforts, I am encountering difficulties in calling upon a second style sheet without it completely overr ...

What is the reason behind the lack of preservation of object state when using Promises?

Here is a code snippet to consider: class ClientWrapper { private client: Client; constructor() { this.client = new Client(); } async connect() : Promise<void> { return this.client.connect(); } async isConne ...

Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application. One of the functions in this library that I find particularly useful is: var defaultDecimalRounding=3 function formatNumber(number) { if (isNaN(number.value) == tr ...

Having trouble with clearing divs function not working as expected

I'm facing a challenge in properly aligning 3 div elements without resorting to adding padding at the bottom of the wrapping div, which isn't the most practical solution. Check out the issue demo here How would you suggest addressing this parti ...

I am facing a problem with the API routes in my Next.js project as the req.query object is coming up as undefined

Issue: I'm facing a problem with accessing query parameters in my API route. Despite sending the correct URL with the query parameter, req.query is returning undefined data instead of the expected values. Here's the Request Handling Code: impor ...