Yasir
Yasir

Reputation: 909

Function Inside of Style Components Passing Variable

I have a list of categories. Each category has its own color. I want to pass the category name as a ref to Style Components and have the Styled Component pass the category as string to a function which maps the string to the appropriate color value.

The idea is to have the category color vals in a separate file and reference them.

I currently have this.

<Container
onClick={playChannel}
category={category}>

const Container = styled.div`
  background: ${colorFromTheme(({ category }) => category)};
`;

const colorFromTheme = val => ({ theme }) => {
  let color = val;
  console.log(val);

  if (Object.keys(theme).includes(val)) {
    color = theme[color];
  }

  return val;
};

This is all currently passing vals along. Theme is a js file of consts that are exported. I am getting an error where val is coming back as a function. However, if I just return val without conditional, I see in Dev Console that the name of the category I pass it comes back.

Any ideas? Thanks.

Upvotes: 0

Views: 1866

Answers (1)

Dusan Jovanov
Dusan Jovanov

Reputation: 567

Just do

<Container onClick={playChannel} background={colorFromTheme(category)}>

and

const Container = styled.div background: ${({background}) => background};

Upvotes: 2

Related Questions