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

1

19

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)
"
Subgroup answered 16/4, 2019 at 22:33 Comment(0)
C
51

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) => props.someNumber};
`
Caprine answered 16/4, 2019 at 23:3 Comment(1)
I editted the typescript 2.9+ version to account for the fact that specifying the props type is unnecessary. That's inferred from the generic parameterLotus

© 2022 - 2025 — McMap. All rights reserved.