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

How can we enforce that only a certain type of ReactElement is allowed to be passed as props to a Component in TypeScript?

eslint and vscode seem to have trouble detecting validation errors when passing incompatible ReactElement types. Despite searching through documentation and examples, I haven't been able to find a solution that works. // Footer.tsx export interface ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

How to retrieve the clicked value using jQuery within a jinja2 loop

I'm currently working on an app that utilizes a Flask backend and Jinja2 templating. Within the HTML, I have a loop set up to organize data into batches, creating three columns on the web page: {% for batch in df.iterrows() | batch(3) %} <d ...

Checking the validity of a username through regex

I have implemented a Username field validation in Vue using regex. A key down event triggers the method below with each keystroke: userNameValidation(event) { if (!event.key.match(/^[a-zA-Z0-9._]+$/)) { event.preventDefault(); } ...

In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am us ...

What is the best way to detect component errors on the server with Angular Universal?

Here is a snippet of my server code that renders the Angular home.component: app.get("*", (req, res) => { res.render( `../${CLIENT_DIST_DIR}/index`, { req: req, res: res, providers: [ ...

Issues encountered when dealing with floating elements and margins

Having some difficulties with aligning elements on my website. As someone who is not highly skilled in coding, I am struggling to define the width and float properties for certain classes. Despite my attempts, it seems that the elements are not positioning ...

Nextjs doesn't render the default JSX for a boolean state on the server side

I am working on a basic nextjs page to display a Post. Everything is functioning smoothly and nextjs is rendering the entire page server side for optimal SEO performance. However, I have decided to introduce an edit mode using a boolean state: const PostPa ...

Implementing dynamic rendering of elements in Next.js using data from FaunaDB

I am currently working on a feature that displays different elements based on the users' job profile status. To fetch the necessary data, I'm utilizing FaunaDB along with useSWR. When I console.log(userData), I receive the following object: jobPr ...

Tips for rendering the title based on the specific ID provided by the API in nextJS

There is an issue I am facing. I only want to show the "title" based on the ID, but currently all the "titles" are showing up at once. You can see it in the image below: https://i.stack.imgur.com/89D6L.png Here's my code: const getData = () => { ...

Determine the height of an element in JavaScript or jQuery by using the CSS property height: 0;

I'm facing a challenge in determining the actual height of an element, which currently has a CSS height property set to: height: 0; When I check the console, it shows a height of 0, but I'm looking to find the real height of the element. I als ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

Utilizing the overflow feature in conjunction with a specified height

Take a look at this image, the overflow:hidden property is not working as expected and some text is still visible that I want to hide without adjusting the height. How can I achieve this? Focusing on the highlighted area in Red, it is causing irritation. ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Developing ES6 modules in C++ using Node.js

Here is a previous example showcasing how to create a Node.js addon in C++: https://nodejs.org/api/addons.html You can use node-gyp to build it into a common JS module, which works well with the 'require' function. However, when trying to impo ...

Analyzing latency in node.js through numerous requests

Is there a way to send multiple requests in a loop, and measure the time of each request? In PHP I'd do: require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); for ($i = 0; $i < 100; $i++) { $start = mic ...

Array contains a copy of an object

The outcome I am striving for is: dataset: [ dataset: [ { seriesname: "", data: [ { value: "123", }, { value: &q ...

What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

Exploring the intricacies of defining Vue component props in TypeScript using Vue.extend()

Here is a simple example to illustrate my question When I directly define my props inside the component, everything works fine <script lang="ts"> import Vue, { PropType } from "vue"; export default Vue.extend({ props: { col ...

Is there a simple solution to show script 1 to visitors from the US and Canada, while displaying script 2 to visitors from other countries?

I'm looking for a simple script that can show one script to visitors from the US and Canada, and another script to visitors from other countries. It doesn't have to be perfect, but using a service like seems too complex for me. Is there a stra ...