Skip to content

Commit

Permalink
feat(wrapper): wrapper component allow to use custom fields
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Wrapper is the new way to register a custom component
  • Loading branch information
jucian0 committed Jan 23, 2022
1 parent ccf09fd commit 16f46ee
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions src/Wrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import React, { Fragment } from 'react'
import { EventChange, Field } from '.'

type Props = {
component: React.JSXElementConstructor<any>
} & any

function WrapperComponent(
{ component, ...rest }: Props,
ref: React.RefObject<Field>
) {
const Component = component
const [value, setValue] = React.useState<any>(null)

function handleOnChange(e: any) {
if (ref.current) {
ref.current.value = e
ref.current?.dispatchEvent(new CustomEvent('input', { detail: e }))
}
}

function handleOnBlur(e: any) {
if (ref.current) {
ref.current.value = e
ref.current?.dispatchEvent(new CustomEvent('blur', { detail: true }))
}
}

function handleEvent(e: EventChange) {
setValue(e.detail ?? e.target.value)
}

React.useEffect(() => {
if (ref.current) {
ref.current.addEventListener('input', handleEvent)
}
return () => {
if (ref.current) {
ref.current.removeEventListener('input', handleEvent)
}
}
}, [ref.current])

return (
<Fragment>
<div ref={ref} hidden />
<Component
{...rest}
value={value}
selected={ref.current?.value}
onChange={handleOnChange}
onBlur={handleOnBlur}
/>
</Fragment>
)
}

export const Wrapper = React.forwardRef(WrapperComponent)

0 comments on commit 16f46ee

Please sign in to comment.