1

I map over an array of colors, which is defined in the database. I want to pass this colors as background for the created divs. Like I am used to, the console shows me, that the colors out of the array are passed in as prop. But using the props in styled components not works in typescript. I tried the following, what I have found in the net:

import * as types from 'styled-components/cssprop'

import type {} from 'styled-components/cssprop';

/// <reference types="styled-components/cssprop" />

I only passed this variations into my file. The both snippets:

<ColorHolder>
    {item.colors.map((color)=>(
     <div color={color}></div>
      ))}
    </ColorHolder>

css:

 & div{
        width:20px;
        height:20px;
        border-radius:50%;
        background:${props=>props.color};
    }

2 Answers 2

2

As far as I understand your code, you don't need to use any libraries. Here is the working example, where colors in the array you fetched from backend

<div>
{
colors.map(color=>(
    <div style={{backgroundColor: color, height: "50px",width: "50px"}}>
    .
    </div>))
}
</div>

Here's full example - codesandbox.io

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was used to take the library, but so it works either.
2

Only styled components can receive props for this style adaptation technique.

Therefore in your case simply create a quick styled div:

const StyledDiv = styled.div<{ color: string }>`
  background: ${props => props.color};
`;

<ColorHolder>
  {item.colors.map((color) => (
    <StyledDiv color={color}></StyledDiv>
  ))}
</ColorHolder>

1 Comment

Thanks ghybs, that's a great tip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.