Created
March 27, 2022 22:41
-
-
Save vasemkin/9edbd23d64ff01e01659f27161ac2a9f to your computer and use it in GitHub Desktop.
Chakra UI Gradient Border HOC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from "react"; | |
| import { ChakraProps, ResponsiveValue } from "@chakra-ui/react"; | |
| import { Property } from "csstype"; | |
| export type ChakraGradientBorderProps = { | |
| borderGradient: ResponsiveValue<Property.Background>; | |
| } & ChakraProps; | |
| export const chakraGradientBorder = <P extends object>( | |
| Component: React.ComponentType<P> | |
| ) => | |
| class ChakraGradientBorder extends React.Component< | |
| P & ChakraGradientBorderProps | |
| > { | |
| render() { | |
| const { | |
| borderGradient, | |
| borderWidth, | |
| borderRadius, | |
| bg = "white", | |
| ...rest | |
| } = this.props; | |
| return ( | |
| <Component | |
| {...componentStyle} | |
| bg={bg} | |
| borderWidth={borderWidth} | |
| borderRadius={borderRadius} | |
| _before={{ | |
| ...beforeStyle, | |
| margin: `-${borderWidth}`, | |
| bg: borderGradient, | |
| }} | |
| {...(rest as P)} | |
| /> | |
| ); | |
| } | |
| }; | |
| const componentStyle = { | |
| borderWidth: ".1rem", | |
| borderRadius: 0, | |
| bg: "white", | |
| pos: "relative", | |
| bgClip: "padding-box", | |
| borderColor: "transparent", | |
| } as ChakraProps; | |
| const beforeStyle = { | |
| content: '""', | |
| pos: "absolute", | |
| zIndex: "-1", | |
| borderRadius: "inherit", | |
| top: 0, | |
| left: 0, | |
| right: 0, | |
| bottom: 0, | |
| } as Pick<ChakraProps, "_before">; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Box } from "@chakra-ui/react"; | |
| import type { NextPage } from "next"; | |
| import { | |
| chakraGradientBorder, | |
| ChakraGradientBorderProps, | |
| } from "@hoc/ChakraGradientBorder"; | |
| const GradientBox = chakraGradientBorder(Box); | |
| const borderGradient = "linear-gradient(to right, blue, red)"; | |
| const Home: NextPage = () => { | |
| return ( | |
| <GradientBox {...gradientBoxStyle}>I have a gradient border!</GradientBox> | |
| ); | |
| }; | |
| const gradientBoxStyle = { | |
| borderWidth: ".2rem", | |
| borderRadius: "1.2rem", | |
| p: "2rem", | |
| borderGradient, | |
| } as ChakraGradientBorderProps; | |
| export default Home; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment