JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 14817
  • Score
    100M100P100Q127445F
  • License MIT

A wrapper around React.forwardRef() that allows HTML attributes and prop types to be derived from the as prop.

Package Exports

  • forward-ref-as
  • forward-ref-as/package.json

Readme


forwardRefAs()

A wrapper around React.forwardRef() that allows HTML attributes and prop types to be inferred from an as prop.
npm i forward-ref-as

Bundlephobia Types Code coverage Build status NPM Version MIT License


Quick start

import forwardRefAs from 'forward-ref-as'
import type {AsProp} from 'forward-ref-as'

// Forwards `ref` to the underlying button and adds strong
// types for the `as` prop.
const Button = forwardRefAs<ButtonProps, 'button'>(
  ({as: As = 'button', ...props}, ref) => <As ref={ref} {...props} />
)

interface ButtonProps {
  as?: AsProp
}

// ✅ Will pass type checking and autocomplete correctly
<Button as='a' href='https://jaredLunde.com'/>

// ❌ Will fail type checking and not autocomplete "href"
<Button href='#'>

API

forwardRefAs()

A wrapper around React.forwardRef() with the same call signature, but a type signature that allows as prop HTML attributes and React prop types to be inferred.

function forwardRefAs<Props, DefaultAs extends AsProp = 'div'>(
  render: React.RefForwardingComponent<
    DefaultAs extends keyof JSX.IntrinsicElements
      ? FromReactType<DefaultAs>
      : DefaultAs,
    Props
  >
): ForwardRefAsExoticComponent<Props, DefaultAs>

LICENSE

MIT