How to pass props to a styled component in emotion? Using TypeScript

Contentop picture Contentop · Apr 17, 2019 · Viewed 7.6k times · Source

I am using styled by emotion at:

import styled from '@emotion/styled'

I am trying to pass props to a styled component like the guide mentions:

https://emotion.sh/docs/styled

It doesn't work for some reason. I use TypeScript as well. I pass props to my styled component called StyleWrapper here:

const ex: React.FunctionComponent<exProps> = props => {
  return (
    <StyleWrapper someNumber = {props.someNumber}
...
    </StyleWrapper >
  )
}

and in StyleWrapper:

const ToolsHeaderColumn = styled.div`
  padding-top: ${props => props.someNumber };
`

What I get is an error in compilation:

"Property 'someNumber ' does not exist on type 
'Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, 
HTMLDivElement>, "children" | "style" | "title" | 
"color" | "hidden" | "defaultChecked" | "defaultValue" |     "suppressContentEditableWarning" | ... 243 more ... 
| "css"> & { ...; }'.ts(2339)
"

Answer

mfakhrusy picture mfakhrusy · Apr 17, 2019

by this docs, you can make it like:

type ToolsHeaderProps = {
  someNumber: number
}
const ToolsHeaderColumn = styled('div')`
  padding-top: ${(props: ToolsHeaderProps) => props.someNumber };
`

if you're using typescript 2.9+, you can use this:

const ToolsHeaderColumn = styled.div<ToolsHeaderProps>`
  padding-top: ${(props: ToolsHeaderProps) => props.someNumber};
`