Last active
September 18, 2022 14:30
-
-
Save crtl/745400a2bd2bfe50abb3af4f23daf40d to your computer and use it in GitHub Desktop.
Function to create function component wrapped in styled component.
This file contains 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 {FC} from "react"; | |
import styled from "styled-components"; | |
/** | |
* Creates a function component and wraps it in styled-component to enable styling | |
* and generates a new displayName for returned component if provided component has one. | |
* Usage: | |
* ``` | |
* const MyComponent = createStyledFC<MyProps>((props) => {})` | |
* background: blue; | |
* | |
* .my-styled { | |
* color: red; | |
* } | |
* `; | |
* ``` | |
* @param component Function component to wrap | |
* @param displayName Optional displayName for component | |
*/ | |
export function createStyledFC<T>(component: FC<T & {className?: string}>, displayName?: string) { | |
const comp = styled(component as FC<T & {className?: string}>); | |
const _displayName = displayName || component.displayName; | |
if (_displayName) { | |
component.displayName = displayName; | |
(comp as any).displayName = `Styled${component.displayName}` | |
} | |
return comp; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment