Search code examples
reactjstypescriptstyled-components

No overload matches this call when using styled-components


There are several questions about this error on SO but none from anybody in a similar situation and none of the solutions I have found work so I'm going to post a specific question.

When using a Styled component inside another component and passing props to it, do I have to create a new type to pass the props through to the styled component or is there some way of using the existing styled component types?

Here is my code. It seems to be the as="" attribute which is giving the error above. I assume this is something to do with the fact that my component only takes the prop so it can pass it to the Styled Component as it is a feator of Styled Components.

import React from 'react'
import styled from 'styled-components'

type Props = {
    additionalClass?: string,
    as?: string
}

const Component: React.FC<Props> = (props) => {

    return (

        <StyledComponent as={props.as} className={props.additionalClass}>
            {props.children}
        </StyledComponent>

    )

}


export default Component


const StyledComponent = styled.div`    
    ...styles go here
`

Solution

  • The problem was that I was trying to pass the "as" prop to styled components and I thought it needed to be a string so I did this...

    type Props = {
        className?: string,
        as?: string
    }
    

    The problem is that once you pass it to styled-components it expects it to be the name of an element. I found the answer on Github and it can be one of two different things. This works...

    type Props = {
        className?: string,
        as?: React.ElementType | keyof JSX.IntrinsicElements
    }