Created
February 13, 2024 19:33
-
-
Save kwabe007/171af308aaf44881e9e1a43aa0a1ff05 to your computer and use it in GitHub Desktop.
How to dispatch an event using pure js on an input element managed by React.
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
// All credits to @kentcdodds | |
// https://github.com/facebook/react/issues/10135#issuecomment-401496776 | |
function setNativeValue(element, value) { | |
const { set: valueSetter } = Object.getOwnPropertyDescriptor(element, 'value') || {} | |
const prototype = Object.getPrototypeOf(element) | |
const { set: prototypeValueSetter } = Object.getOwnPropertyDescriptor(prototype, 'value') || {} | |
if (prototypeValueSetter && valueSetter !== prototypeValueSetter) { | |
prototypeValueSetter.call(element, value) | |
} else if (valueSetter) { | |
valueSetter.call(element, value) | |
} else { | |
throw new Error('The given element does not have a value setter') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment