Skip to content

Commit

Permalink
Merge pull request #277 from mediamonks/polymorphic-props
Browse files Browse the repository at this point in the history
Add PolymorphicComponentProps
  • Loading branch information
leroykorterink authored Feb 16, 2024
2 parents 8c7973d + 98720a7 commit 98bbbb9
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export * from './lifecycle/hooks/useIsMountedState/useIsMountedState.js';
export * from './lifecycle/hooks/useMount/useMount.js';
export * from './lifecycle/hooks/useUnmount/useUnmount.js';
export * from './nextjs/useIsomorphicLayoutEffect/useIsomorphicLayoutEffect.js';
export * from './types/PolymorphicComponentProps/PolymorphicComponentProps.js';
export * from './utils/adjustFontSize/adjustFontSize.js';
export * from './utils/arrayRef/arrayRef.js';
export * from './utils/createTimeout/createTimeout.js';
Expand Down
85 changes: 85 additions & 0 deletions src/types/PolymorphicComponentProps/PolymorphicComponentProps.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { Meta } from '@storybook/blocks';

<Meta title="Types / PolymorphicComponentProps" />

# PolymorphicComponentProps

A collection of generic types to help build strongly typed Polymorphic Components, consistently.

`PolymorphicComponentProps` takes care of combining your Component's unique prop types with those of
any HTML element or React Component you happen to be assigning to your Polymorphic Component. As an
extra precaution, a check is performed to omit any "default" prop type from the chosen element that
might conflict with one of the same name in your Component.

## Usage

```tsx
type FooComponentProps<T extends ElementType> = PolymorphicComponentProps<
T,
{ barProp: string | undefined }
>;

type FooComponent = <T extends ElementType>(props: FooComponentProps<T>) => ReactNode | null;

export const Foo: FooComponent = <T extends ElementType>({
as: Component = 'div',
children,
...otherProps
}: FooComponentProps<T>) => {
return <Component {...otherProps}>{children}</Component>;
};
```

The type `FooComponentProps` consists of `T` and any custom prop types you require for
`<FooComponent />` (in this example, `barProp`). The types for `T` are derived from the element in
the `as` prop:

```tsx
<Foo as="a" href="https://media.monks.com" barProp="baz">
This is a proper link
</Foo>

<Foo as="h1">
Foo as a heading: anything goes.
</Foo>
```

So while two examples use the same FooComponent, their `FooComponent` types are not the same. They
are derived from the types from their respective `<a />` and `<h1 />` elements.

```tsx
<Foo as="button" href="https://example.com">
This button will throw an error
</Foo>

<Foo as="button" onClick={() => console.log("Clicked")}>
This button is okay
</Foo>
```

### Using Refs

A Polymorphic Component with Refs can be typed with `PolymorphicComponentPropsWithRef` and
`PolymorphicRef`:

```tsx
type FooComponentProps<T extends ElementType> = PolymorphicComponentPropsWithRef<
T,
{ barProp: string | undefined }
>;

type FooComponent = <T extends ElementType>(props: FooComponentProps<T>) => ReactNode | null;

export const Foo: FooComponent = forwardRef(
<T extends ElementType>(
{ as: Component = 'div', children, ...otherProps }: FooComponentProps<T>,
ref?: PolymorphicRef<T>,
) => {
return (
<Component {...otherProps} ref={ref}>
{children}
</Component>
);
},
);
```
31 changes: 31 additions & 0 deletions src/types/PolymorphicComponentProps/PolymorphicComponentProps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type {
ComponentPropsWithoutRef,
ComponentPropsWithRef,
ElementType,
PropsWithChildren,
} from 'react';

/**
* PropsFromAs is a type based on the supplied as prop.
*/
type PropsFromAs<Type extends ElementType> = { as?: Type };

/**
* MergeAndOverride is a type that omits type keys from BaseTypes that are also present in OverrideProps.
*/
type MergeAndOverride<BaseType, OverrideProps> = Omit<BaseType, keyof OverrideProps> &
OverrideProps;

export type PolymorphicRef<Type extends ElementType> = ComponentPropsWithRef<Type>['ref'];

export type PolymorphicComponentProps<
BaseType extends ElementType,
OwnProps = Record<string, never>,
> = PropsWithChildren<
MergeAndOverride<ComponentPropsWithoutRef<BaseType>, PropsFromAs<BaseType> & OwnProps>
>;

export type PolymorphicComponentPropsWithRef<
BaseType extends ElementType,
OwnProps = Record<string, never>,
> = PolymorphicComponentProps<BaseType, OwnProps> & { ref?: PolymorphicRef<BaseType> };

0 comments on commit 98bbbb9

Please sign in to comment.