Patryk Janik
Patryk Janik

Reputation: 2623

Iterations inside of styled components

I've got theme object which looks like:

{
  h1: {
    color: red
  },
  h2: {
    color: blue
  }
}

And I would like to iterate through that object and dynamically create styled-component style definitions like:

createGlobalStyle`
   ${props => Object.keys(props.theme).map(header => {
     return css`
     ${header}: {
       color: ${props.theme[header].color;
     }
     ` 
   }
`

The problem is that it is not working :(

Have you maybe idea how to do so basic stuff like iterating through the object and dynamically create additional tagged styles?

Upvotes: 0

Views: 1966

Answers (1)

Ricardinho
Ricardinho

Reputation: 1339

Firstly your createGlobalStyle code example is a bit of a mess missing closing ) and } all over.

Secondly Object.keys(props.theme).map(...) will return an Array.

You should be aiming to at least return a Template literal from that example block.

Thirdly, CSS classes targeting tagnames aren't defined with colons:

${header}: {
    color: ${props.theme[header].color;
}

Here's a working example:

${({ theme }) => {
    let templateLiteral = ``;
    Object.keys(theme).forEach(n => {
        templateLiteral += `
            .${n} {
                color: red;
            }
        `;
    });
    return templateLiteral;
}}

Upvotes: 4

Related Questions