Fix styled-components withComponent Method

This is a note titled "2019-04-22-styled-components-with-component" taken from my note Library. Return to Library.

styled-components have deprecated the withComponent method in favour of the inline as prop. Unfortunately, @types/styled-components says you should use withComponent method and not the as prop.


Here’s a higher-order component you can use instead of either of them.

import styled, { StyledComponent }
from "styled-components"

function withComponent<
  C extends StyledComponent<any, any>,
  T extends React.ComponentType<any>
    | keyof JSX.IntrinsicElements
>(Component: C, type: T) {
  return styled((props =>
    <Component as={type} {...props} />)
     as unknown as T)``

// Example Usage:

const Link = withComponent(Button, 'a');