Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TypeScript and Styled Components `as` prop

I have a styled button:

import { Link } from 'react-router-dom'
import styled from 'styled-components'

const Button = styled(Link)`
  display: block;
  border: 1px solid white;
  padding: 5px; 
`

I can use it as a Link:

<Button to='/' />

But sometimes I would like to use it as an a:

<Button as='a' href='/' />

But in a second case TypeScript is complaining with:

Type '{ children: string; as: string; href: string; }' is not assignable to type 'Readonly<ThemedOuterStyledProps<WithOptionalTheme<LinkProps, any>, any>>'.
Property 'to' is missing in type '{ children: string; as: string; href: string; }'.

"as" polymorphic prop

like image 548
Kocur4d Avatar asked Nov 09 '18 16:11

Kocur4d


1 Answers

TypeScript is complaining because your Link component that comes from react-router requires you to specify a to prop. I am not sure what you are trying to achieve, but Link should already render as an <a /> tag.

If you are willing to render a link to, let's say, an external website, you probably don't want to use a styled(Link), but a styled.a.

If you worry about repeating your style for both the styled(Link) and styled.a, you'd probably want to write a reusable button style using the css helper function and include it in both of your styled components.

Unfortunately, I believe it is the only option for now, as I have been in a similar case, and tried using as={Link} on a styled.a and TypeScript complains about unrecognised props. I believe that the implementation of the polymorphic as prop on TypeScript is not fully functional so there might be a fix later on.

like image 171
Tydax Avatar answered Oct 09 '22 01:10

Tydax