Home > Net >  How to use styled-component CSS props with Typescript
How to use styled-component CSS props with Typescript

Time:09-29

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

CodePudding user response:

As far as I understand your code, you do 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

CodePudding user response:

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>
  • Related