Skip to content
This repository has been archived by the owner on Jun 5, 2024. It is now read-only.

Commit

Permalink
fix: manually trigger native event on clear (#106)
Browse files Browse the repository at this point in the history
* fix: manually trigger native event on clear

* release
  • Loading branch information
Jaeho Lee authored Dec 14, 2022
1 parent 295a4f8 commit 9914a6b
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/eight-crews-refuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@greenlabs/formula-components": patch
---

fix: manually trigger native event on clear
8 changes: 8 additions & 0 deletions packages/components/src/TextField/TextField.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,14 @@ export const Textarea_and_Ref_Etc: ComponentStory<typeof TextField> = (
hideClearButton: true,
}}
/>
<TextField
{...args}
onChange={(e) => {
const { value } = e.target
console.log(value)
}}
titleText="onChange: see console"
/>
</form>
)}
/>
Expand Down
3 changes: 2 additions & 1 deletion packages/components/src/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
import type { IconProps } from "../Icon"
import { DeleteFill } from "../Icon"
import { COMPONENT_CLASS, stateClass } from "./common"
import { triggerNativeEventFor } from "../utils/event"

type sizeVariantKey = keyof typeof textFieldSizeVariants
type variantKey = keyof typeof textFieldVariants
Expand Down Expand Up @@ -193,7 +194,7 @@ export const TextField = React.forwardRef<InputElement, TextFieldProps>(
onClick={(_) => {
const inputEl = inputRef.current
if (inputEl) {
inputEl.value = ""
triggerNativeEventFor(inputEl, { event: "input", value: "" })
}
}}
>
Expand Down
23 changes: 23 additions & 0 deletions packages/components/src/utils/event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* inspired by https://stackoverflow.com/a/71340077
* triggerNativeEventFor(inputRef.current, { event: 'input', value: '' });
* triggerNativeEventFor(checkBoxRef.current, { event: 'input', checked: false });
*/
export function triggerNativeEventFor<T>(
element: T,
{
event,
...valueObj
}: { event: keyof HTMLElementEventMap; [key: string]: string }
) {
if (!(element instanceof Element)) {
throw new Error(`Expected an Element but received ${element} instead!`)
}

const [prop, value] = Object.entries(valueObj)[0] ?? []
const prototype = Object.getPrototypeOf(element)
const desc = Object.getOwnPropertyDescriptor(prototype, prop)

desc?.set?.call(element, value)
element.dispatchEvent(new Event(event as string, { bubbles: true }))
}

0 comments on commit 9914a6b

Please sign in to comment.