Skip to content

Instantly share code, notes, and snippets.

@crtl
Last active September 18, 2022 14:30
Show Gist options
  • Save crtl/745400a2bd2bfe50abb3af4f23daf40d to your computer and use it in GitHub Desktop.
Save crtl/745400a2bd2bfe50abb3af4f23daf40d to your computer and use it in GitHub Desktop.
Function to create function component wrapped in styled component.
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