Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No overload matches this call when usign 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
`
like image 458
jonhobbs Avatar asked May 12 '20 19:05

jonhobbs


2 Answers

You just need to validate the prop when you are creating the styled.div

Example

const Menu= styled.div<{ menuOpen: boolean }>`
  ${({ menuOpen }) => {
    if (menuOpen) {
      return 'background-color: white';
    }

    return 'background-color: black';
  }}
`;

export const Component: React.FC = () => {
  const [menuOpen, setMenuOpen] = useState(false);

  return(
    <Menu menuOpen={menuOpen}>
      whatever content
    </Menu>
  )
}
like image 87
Brandon Avatar answered Oct 19 '22 18:10

Brandon


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
}
like image 26
jonhobbs Avatar answered Oct 19 '22 19:10

jonhobbs