-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(wrapper): wrapper component allow to use custom fields
BREAKING CHANGE: Wrapper is the new way to register a custom component
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |