<h1 align="center">@polymorphic-factory/react</h1>
npm install @polymorphic-factory/react
Create polymorphic React components with a customizable styled function.
A polymorphic component is a component that can be rendered with a different element. This is useful
for component libraries that want to provide a consistent API for their users and want to allow them
to customize the underlying element.
``bash`
npm install @polymorphic-factory/react
or
`bash`
yarn add @polymorphic-factory/react
or
`bash`
pnpm install @polymorphic-factory/react
Import the polymorphic factory and create your element factory.
`ts`
import { polymorphicFactory } from '@polymorphic-factory/react'
const poly = polymorphicFactory()
You can override the default implementation by passing styled function in the options.
`tsx
const poly = polymorphicFactory({
styled: (component, options) => (props) => {
const Component = props.as || component
return
},
})
const WithOptions = poly('div', { hello: 'world' })
const App = () => {
return (
<>
{/ renders /}
{/ renders /}
>
)
}
`
Use the element factory to create elements inline.
Every JSX element is supported div, main, aside, etc.
`tsx`
<>
>
Use the factory to wrap custom components.
`tsx
const OriginalComponent = (props) =>
const MyComponent = poly(OriginalComponent)
const App = () =>
// render
It still supports the
as prop, which would replace the OriginalComponent.`tsx
// renders
`Refs
You can use
ref on the component, and it will have the correct typings.`tsx
const App = () => {
const ref = React.useRef(null)
return
}
`Types
`ts
import type { HTMLPolymorphicComponents, HTMLPolymorphicProps } from '@polymorphic-factory/react'type PolymorphicDiv = HTMLPolymorphicComponents['div']
type DivProps = HTMLPolymorphicProps<'div'>
``MIT © Tim Kolberger