styled-components / xstyled

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

Extend X to Custom React components #306

Closed ion-willo closed 2 years ago

ion-willo commented 2 years ago

💬 Questions and Help

Hi,

I can't seem to find this anywhere, but is there a way to extend my custom components, or 3rd party libraries, such as React Router's Link to use X?

Regards,

Willo

xesrevinu commented 2 years ago

Hi,

After spending 10 minutes researching the code, I got two ways to do it. I hope this helps you.

import styled, { x } from "@xstyled/styled-components"
import { Link, NavLink, LinkProps } from "react-router-dom"

// or NavLink
const CustomLink = styled(Link)`
  border: 1px solid red;
  ${(props) => {
    return {
      color: props.theme.colors["red-500"],
      fontSize: props.theme.fontSizes.lg,
    }
  }}
`

const ButtonLink: FunctionComponent<LinkProps> = ({ to, children }) => {
  return (
    <x.button color="blue-500" onClick={() => history.push(to)}>
      {children}
    </x.button>
  )
}

<CustomLink to="/page1">
    CustomLink
</CustomLink>

Or use the Link components components props


<Link to="/page2" component={ButtonLink}>
    ButtonLink
</Link>

And then got 😎

image

xstyled is great!

gregberge commented 2 years ago

Thanks @piggy-kee for your answer!

ion-willo commented 2 years ago

Thanks @piggy-kee , but maybe I wasn't clear. I'd like to be able to do something like this:

<MyLink w={120} color='emerald-500'>My special link</MyLink>

Over the weekend I came across this:

import { system } from '@xstyled/system'

export const Wrapper = styled.div`
  ${system}
`

Which now allows me to do exactly that!

PS also found it in the docs 🙈 here: https://xstyled.dev/docs/magic-styled-components/#add-utility-props-to-styled-components