Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PolymorphicComponentProps #277

Merged
merged 7 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
nswaldman marked this conversation as resolved.
Show resolved Hide resolved

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> };
Loading