Search code examples
javascriptcssreactjsemotion

React.js: Is there a way to apply a separate style to a component to be rendered in array.map?


The following demo uses array.map to render three blocks.

demo(CodeSandBox)

The names of the colors are defined in Colors.tsx.

export default {
  foo: "#ff6347",
  bar: "#4682b4",
  baz: "#90ee90"
};

Is there a way to change the color of a block rendered by array.map individually using the color you defined?

I use Emotion for CSS in JS.


Below is the entire code.

/** @jsx jsx */
import { jsx, css } from "@emotion/core";
import colors from "./Colors";

export default function App() {
  const colorName = ["foo", "bar", "baz"];
  const Block = colorName.map((item, index) => {
    const blockStyle = css`
    ${baseStyle}
    background-color: ${colors.foo}; // ${colors.item} did not work.
  `;
    return (
      <li key={index}>
        <span>{item}</span>
        <div css={blockStyle} />
      </li>
    );
  });

  return <ul>{Block}</ul>;
}

const baseStyle = css`
  width: 100px;
  height: 100px;
`;

Solution

  • tldr

    background-color: ${colors[item]};
    

    colors is an object. colorName => color

    To access a color by colorName you can use colors[colorName]

    Thus in your code:

    background-color: ${colors[colorName]}
    

    or (since you named the colorName item)

    background-color: ${colors[item]};