How can I dynamically set style of a mapped element without using inline styling?

Viewed 262

I'm coding a React function with parent component containing an array of objects:

let const ingredients = [
    {name:"lettuce",color:"green"},
    {name:"tomato",color:"red"}
]

...

In a child component, there is a map function that breaks down an array to single items to be displayed in a div.

What is the best practice for defining CSS styling for an object className:"name" to set backgroundColor: {ingredient.color};? I'm trying to avoid manual entry of the entire set of key/values of 'ingredients', to allow updating the object without breaking the code.

I'm currently using inline styling, which I have been advised against. Currently using:

let burg = props.toppings.map((item) => {
const divColor = {backgroundColor: item.color};
return (<div style={divColor}>{item.name}</div>)
3 Answers

Inline style is bad when you have other solution to do what you want. Here, you have a string that is the color (red, green, etc.) so you could write a css class for every color, but that is of course a really bad idea. Inline style is the good way to do it here.

I would suggest setting the class of the div instead of the style. That way you can change the look without resorting to inlining the style.

You could create a css class for lettuce with the background color green, instead of using the item.color you'd set class={ item.name }

You can use this way.

css can be more handy if you use scss

// css
.color-green {
  color: green;
}
.color-red {
  color: red;
}
import React from "react";
import "./styles.css";

const ingredients = [
  { name: "lettuce", color: "green" },
  { name: "tomato", color: "red" }
];
const Vegetable = ({ color, text }) => {
  return (
    <p>
      this is <span className={`color-${color}`}>{text}</span> color{" "}
    </p>
  );
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {ingredients.map((item, index) => {
        return <Vegetable key={index} color={item.color} text={item.name} />;
      })}
    </div>
  );
}
Related