What is the best method to incorporate a JavaScript object key's value into CSS styling?

I am currently working on a project in React where I'm iterating over an array of objects and displaying each object in its own card on the screen. Each object in the array has a unique hex color property, and my goal is to dynamically set the font color of each card using Sass/CSS based on the color value stored in the object. However, I am struggling to find a way to pass this color value to my stylesheet.

// Defining the array I'm mapping over
const data = [
   {
    title: 'this is the title of object one',
    color: #979696
  },
   {
    title:'this is the title of object two',
    color: #8C64E6
  }
]
// Component to render individual cards

const Card = (props) => (
  <h3 className='title'>{props.title}</h3>
)
// CSS
.title {
  color: ????; 
}

Answer №1

If you're not utilizing a CSS-in-JS solution like styled components, there is no direct way to pass styles to your Sass files.

But in this particular scenario, you could consider the following approach:

const card = props => (
  <h3 
    className='title'
    style={{ color: props.color }}
  >
    {props.title}</h3>
)

Answer №2

When working with JSX, you have the ability to include inline CSS. If you are passing styles as props within an object labeled styleObject, it is possible to incorporate the color property in this manner:

const Card = props => {
    const color = props.styleObject.color
    const title = props.styleObject.color
    return (
        <h3 style={{ color: color }}>{title}</h3>
    )
}

In addition, if there is a need to display a heading for each object contained in your array, here's how you can achieve it:

const Cards = props => {
    const array = props.array
    return array.map(heading => (
        <h3 key={heading.title} color={heading.color}>
            {title}
        </h3>
    ))
}

Answer №3

It is unclear whether I understand your query correctly, but you have the option to apply inline styling directly

const array = [
   {
    title: 'the title of object one',
    color: #979696
  },
   {
    title:'the title of object two',
    color: #8C64E6
  }
]
// formatting the array values for component

const card = props => (
  <h3 style={{color:a.color}}>{props.title}</h3>
)

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 cookie fails to correctly establish itself

I have been using Vite to develop a React app that I deploy on Firebase for hosting the web application. To handle the backend, I am utilizing NodeJS with Express. Since I was unsure where to deploy my server, I opted to use ngrok on the port my server is ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

Firefox users may notice that the pop-up video player appears in unusual locations on their screen

I'm encountering an issue with a pop-up video player that is triggered by an "onClick" event in HTML elements. The problem arises when there are multiple video players on the same page - in Firefox, the first video loads at the bottom of the page, req ...

jQuery - Modify Turn.js to exclusively implement the page Peel effect

I am attempting to implement the peel effect from turn.js into my code, where hovering over the bottom right corner of the page causes it to peel slightly and appear as if it is bending upwards. I specifically want only the peel effect and not the entire ...

Preventing access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

Styling certain UL and LI elements with CSS properties

Greetings everyone! I constantly struggle when it comes to making my CSS cooperate. I have some code that involves using ul and li tags. However, I only want to apply that styling to specific sections of my HTML code rather than all instances of the ul and ...

Is there a way to remove the ring shadow in TailwindCSS?

Here is a visual representation of the issue I'm facing (refer to the image): Check out the Image After inspecting with Chrome, it seems like the problem is connected to --tw-ring-shadow. I attempted to use classes like ring-0 and ring-offset-0 (men ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

How can I retrieve console log information in POSTMAN when a test fails?

Having an issue with this test. I am trying to trigger a console.log when the installment value in my JSON is less than 100 (resulting in a test FAIL). However, I am receiving both PASS and FAIL results in the test, but no information is showing up in th ...

Use of absolute positioning resulted in the disappearance of the element

Can anyone assist with resolving the issue I am encountering? I currently have three nested divs as follows: <div class="section"> <div class="parent"> <div class="child"> Some random text. </div> </div> </div> To adj ...

Receiving an absence of string or a null value from a text box

My goal is to test the functionality of an <input> element by entering text into a textbox and then displaying that data in the console. However, I am encountering issues with retrieving and printing the content. Additionally, I am interested in test ...

javascript guide to dynamically update the glyphicon based on value changes

I am attempting to implement an optimal level feature where a glyphicon arrow-up will be displayed if a value falls within the optimum range, and it will switch to a glyphicon arrow-down if the value is lower. <div class="card-body" ng-repeat="item i ...

Tips for customizing the icons and properties of the edit and delete buttons on the editable Material-table

I am currently working with material-table and editable functionality. I have successfully added the functions "onRowUpdate" and "onRowDelete", however, I would like to customize the icons for these buttons, adjust their spacing, and change their size. I h ...

Creating a Custom Alert Box in Javascript with Image Alignment

I have just finished creating a custom alert box using Javascript, complete with text and images. However, I am facing an issue with alignment. The output is not as expected. I am trying to display the correct mark and text on the same line. Can someone ...

Retrieve an item from a mapped array

Currently, I am using the following code snippet console.log('errors: ' + password.get('errors')); to check the output from password.get('errors'));, and in the console, the response is as follows: List [ Map { "id": "validat ...

Guide on configuring Angular validation to trigger on blur events and form submission

Validation in Angular is currently set to update on model change, but this method can be unfriendly for user interface as it displays errors upon keyup. An optimal solution would involve displaying error messages on blur and also on form submission. After ...

Initiate an Ajax request solely for the elements currently visible on the screen

I am currently facing an issue that requires a solution. Within our template, there are multiple divs generated with the same classes. Each div contains a hidden input field with the ID of the linked target site. My task is to utilize this ID to make aja ...

In a lineup of items arranged horizontally, the second to the last item is perfectly centered, whereas the final item stretches out to occupy all of the leftover

I am currently working on creating a horizontal list of items: My goal is to have the second last item centered once the end of the list is reached, with the last item expanding to fill all remaining space. While I have successfully created the list of i ...

Divide the identical elements and distinct elements from a provided array into two separate arrays storing unique elements and recurring elements

Can anyone help me with this query? I have an array of objects that need to be separated into repeating and non-repeating objects based on the segments they belong to, each in a separate array. For example- [ {name:"abc",id:1,segments:[1,2]}, {n ...