styled-components / xstyled

A utility-first CSS-in-JS framework built for React. 💅👩‍🎤⚡️
https://xstyled.dev
MIT License
2.28k stars 105 forks source link

Generic heading primitive #227

Closed incompletude closed 3 years ago

incompletude commented 3 years ago

I'm trying to implement a generic heading using xstyled but I'm failing at it and could not find any examples around. I think it would be nice to have such a common implementation at the docs. Can someone provide some code?

import { x } from "@xstyled/styled-components"
import { ReactNode } from "react"

type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6
  children?: ReactNode
}

const Heading = (props: Props) => {
  return <x.h1 {...props} />
}

export default Heading
gregberge commented 3 years ago

Hello @incompletude,

import { x } from "@xstyled/styled-components"
import { ReactNode } from "react"

type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6
  children?: ReactNode
}

const Heading = ({ level, ...props }: Props) => {
  const Component = x[`h${level}`]
  return <Component {...props} />
}

export default Heading
incompletude commented 3 years ago

I'm getting the following error at x[`h${level}`]:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ extend<TExtendProps extends object>(...generators: StyleGenerator[]): any; } & { symbol: StyledComponent<(props: Omit<SVGProps<SVGSymbolElement>, "color">) => ReactElement<any, "symbol">, DefaultTheme, SystemProps<...>, "color">; ... 173 more ...; view: StyledComponent<...>; }'.

I think this is the biggest downside of this ecosystem and typescript: error messages are very cryptic.

gregberge commented 3 years ago

Yes, you should learn about TypeScript before using it. You have to cast it to a JSX element. I will lock this issue since it is a TypeScript problem and not a xstyled problem.