Search code examples
reactjstypescriptstyled-components

How to set type of React Functional Component property to Styled Component `styled.div`?


import React, { FunctionComponent } from "react"
import styled from "styled-components"

interface ChildProps {
  color: string
}

const Child = styled.div`
  background-color: ${(props: ChildProps) => props.color};
`

interface ParentProps {
  node: FunctionComponent<ChildProps> // How to set node type to Styled Component `styled.div`?
}

const Parent = function(props: ParentProps) {
  const Node = props.node
  return <Node color="white" />
}

Solution

  • npm install -D @types/styled-components
    
    import styled, { StyledComponent } from "styled-components";
    
    interface ParentProps {
      node: StyledComponent<"div", any, ChildProps, never> 
    }
    

    You can btw look up the type of something e.g. by hovering over it in VSCode.


    Tip: Use a generic to declare the styled-component's props, instead of declaring it in the function. And in this case you can destructure the color.

    const Child = styled.div<ChildProps>`
      background-color: ${({ color }) => color};
    `