A small helper to create a React friendly component that uses a Web Component under the hood.
To create a React wrapper of a Web Component simply use the createWrapper
helper of paperthin
.
import { forwardRef } from 'react'
import { createWrapper } from '@catastic/paperthin'
// The props interface
import type { WebComponentProps } from 'some/model/file'
// The Web Component class
import type { WebComponentClazz } from 'some/file'
// The Web Component tag name
import { WebComponentTag as tagName } from 'some/model/file'
// The proper props
type ReactProps = HTMLAttributes<WebComponentProps>
export const ReactComponentWithChildrenWrapper = forwardRef<
WebComponentClazz | null,
ReactProps
>((props, ref) => createWrapper<WebComponentClazz>({ tagName, props, ref }))
// Alternatively, if your component has a default slot, you can pass `children` along
export const ReactComponentWrapper = forwardRef<
WebComponentClazz | null,
ReactProps
>(({ children, ...props }, ref) =>
createWrapper<WebComponentClazz>({ tagName, children, props, ref })
)
On top of the default slot, you can also forward ReactElement
props to actual slot elements with the help of the slottedNode
helper function.
export const ReactComponentWrapper = forwardRef<
WebComponentClazz | null,
ReactProps
>(({ emoji, children, ...props }, ref) =>
createWrapper<WebComponentClazz>({
tagName,
props,
children: (
<>
{children}
{emoji && slottedNode(emoji, 'emoji')}
</>
),
ref,
})
)
Simply clone this repository and run the dev
command
yarn dev
It will open a local server at port 3000
.