createPolymorph
Creates a polymorphic component.
This combines user-provided props P
with derived native props of element T
.
Exposes as
prop to allow root element, and its native attribute types, to
be changed. Changing the as
prop will also change the ref
type. Accepts
any native Element
tag name (‘div’, ‘input’, ‘button’), or a custom React
component.
Optionally accepts a config C
type to fine-tune the attributes exposed
to consumers and their types.
-
overrides
allows modification of derived native props. -
omit
allows removal of props from the resulting polymorphic component. -
@param
render
- Render function ofPolymorphicExoticComponent
. -
@returns
PolymorphicExoticComponent
Example
type ButtonProps = { variant: 'success' | 'error' }
type ButtonConfig = {
// Remove 'reset' prop from type 'button'
overrides: { type: 'button' | 'submit' },
// Disallow custom `children`
omit: 'children'
}
const Button = createPolymorph<
ButtonProps,
'button',
ButtonConfig
>(({ as: Tag = 'button', type, variant, ...rest }) => {
return (
<Tag {...rest}>
{variant === 'success' ? 'Yaay!' : 'Oh dear...'}
</Tag>
)
})
PolymorphicElement
Return type of PolymorphicExoticComponent
.
Functionally similar to ReactNode
, but with additional restrictions.
PolymorphicProps
Derives the entire set of props for a polymorphic component, combining
user-provided props P
, with derived native props of element T
whilst
attaching "as"
and "ref"
props to provide polymorphism support.
PolymorphicRenderFunction
Render function of createPolymorph
.
Enriches polymorph development typings, allowing default native props to be
derived by the initial as
prop (type T
). This will not affect the
consumer-facing API, only the component implementation.
PolymorphicExoticComponent
Return type of createPolymorph
.
Enriches polymorph consumer typings, allowing changes to as
redefine the
ElementType
and its native attributes. These changes will not affect types
within component implementation; only the consumer-facing API.