Registry / web-framework / react-polymorphed

react-polymorphed

JSON →
library2.2.2jsnpmunverified

react-polymorphed is a TypeScript-focused utility library designed to simplify the creation of type-safe polymorphic React components. It provides a set of types and helper functions that enable components to render as different HTML elements or other React components via an `as` prop, while maintaining strong type inference and preventing common prop errors. Currently at version 2.2.2, the library is actively maintained, with a release cadence typical for a utility focused on React type enhancements, responding to changes in React or TypeScript. Its key differentiator is the comprehensive support for `forwardRef`, `memo`, and `lazy` with polymorphic types, building on foundations laid by `react-polymorphic-types` to offer a robust and developer-friendly experience for complex component patterns.

npm install react-polymorphed
INSTALL
IMPORT
SIG · REACT-POLYMORPHED
R
react-polymorphed
web-frameworkjavascriptv2.2.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PolymorphicComponent
✓ import { PolymorphicComponent } from 'react-polymorphed';
✗ const PolymorphicComponent = require('react-polymorphed').PolymorphicComponent;
Primary type for creating basic polymorphic components. Always use named import, intended for TypeScript projects.
PolyRefFunction
✓ import { PolyRefFunction } from 'react-polymorphed';
A type helper for correctly casting `React.forwardRef` to support polymorphic components with ref forwarding. This is crucial for maintaining type safety for the `ref` prop across different `as` values.
PolyMemoComponent
✓ import { PolyMemoComponent } from 'react-polymorphed';
✗ import { PolyForwardMemoComponent } from 'react-polymorphed';
Use `PolyMemoComponent` for polymorphic components wrapped with `React.memo` that *do not* forward refs. If your component *does* forward refs, you must use `PolyForwardMemoComponent` instead to preserve the ref type correctly.
OnlyAs
✓ import { OnlyAs } from 'react-polymorphed';
A utility type for constraining the allowed values of the `as` prop. However, consider the package's FAQ as usage of `OnlyAs` might introduce more issues than benefits.

This quickstart demonstrates how to create a ref-forwarded polymorphic `Button` component using `react-polymorphed`. It shows the casting of `forwardRef` to `PolyRefFunction`, defines component-specific props, and illustrates how the `as` prop dynamically changes the rendered element and its associated types, preventing invalid prop usage.

import React, { forwardRef, useRef } from 'react'; import { PolyRefFunction } from 'react-polymorphed'; // Cast forwardRef to PolyRefFunction for type-safe ref forwarding in polymorphic components const polyRef = forwardRef as PolyRefFunction; type ButtonProps = { size?: 'small' | 'large'; children: React.ReactNode; }; // Create a polymorphic button component that supports ref forwarding const Button = polyRef<'button', ButtonProps>( ({ as: As = 'button', size, children, ...props }, ref) => { const sizeClass = size === 'small' ? 'px-2 py-1 text-sm' : 'px-4 py-2 text-base'; return ( <As ref={ref} className={`bg-blue-500 text-white rounded ${sizeClass}`} {...props} > {children} </As> ); } ); // Example usage of the polymorphic button const App = () => { const buttonRef = useRef<HTMLButtonElement>(null); const anchorRef = useRef<HTMLAnchorElement>(null); return ( <div className="p-4 flex flex-col gap-4"> <Button type="submit" size="small" ref={buttonRef}> Submit Button </Button> <Button as="a" href="https://example.com" target="_blank" size="large" ref={anchorRef}> Link to Example </Button> {/* This would cause a type error as 'div' does not have 'href' */} {/* <Button as="div" href="#">Div as Link</Button> */} {/* This would cause a type error due to ref mismatch */} {/* <Button as="div" ref={buttonRef}>Div with Button Ref</Button> */} </div> ); }; export default App;
Debug
Known issues
gotchaThe `OnlyAs` constraint feature, designed to restrict the `as` prop to a specific set of elements, may lead to more harm than good and is generally discouraged by the library maintainer. It could complicate type inference or prevent desired flexibility.
fix
Before using `OnlyAs`, thoroughly review the package's FAQ section concerning constraints. Often, relying on TypeScript's natural type inference without explicit `OnlyAs` offers better flexibility and maintainability.
affects: >=2.0.0
gotchaWhen using `React.memo` or `React.lazy` with a polymorphic component that also uses `forwardRef`, it's critical to use the correct wrapper types: `PolyForwardMemoComponent` or `PolyForwardLazyComponent`. Failing to do so will result in incorrect ref type inference and potential runtime errors related to ref properties.
fix
Always use `PolyForwardMemoComponent` for memoized ref-forwarding polymorphic components and `PolyForwardLazyComponent` for lazily loaded ones. For components without ref forwarding, use `PolyMemoComponent` or `PolyLazyComponent` respectively.
affects: >=2.0.0
Errors
Common errors & fixes
Type '{ href: string; }' is not assignable to type 'IntrinsicElements["button"]'. Property 'href' does not exist on type 'IntrinsicElements["button"]'.
Attempting to pass an `href` prop to a polymorphic component when its `as` prop is implicitly or explicitly set to a non-anchor HTML element (e.g., a `button` or `div`). The types correctly prevent invalid props for the resolved element.
fix
Ensure that the `as` prop matches the intended HTML element that supports the given props. For `href`, set `as="a"`.
Type 'RefObject<HTMLButtonElement>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'. Type 'RefObject<HTMLButtonElement>' is not assignable to type 'RefObject<HTMLDivElement>'. The types of 'current' are incompatible.
A `ref` type mismatch occurs when a `ref` object intended for one HTML element type (e.g., `HTMLButtonElement`) is passed to a polymorphic component rendering a different element type (e.g., `div`), or when the `as` prop points to a component that doesn't support refs.
fix
Ensure the `ref` object's generic type matches the HTML element type specified by the `as` prop, or ensure the component specified by `as` actually supports refs. `react-polymorphed` uses `PolyRefFunction` to correctly infer the ref type based on `as`.
Upgrade
Version history
2.2.2latest on npm
Audit
Dependencies
@types/reactrequiredPeer dependency required for React type definitions, essential for type-safe polymorphic components.
Agent activity
2 hits · last 30 days
node
2
Resources
react-polymorphed — npm install react-polymorphed · libregistry