Search code examples
reactjstypescriptstyled-components

How to use styled-component CSS props with Typescript


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};
    }

Solution

  • 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