Home > Mobile >  React onChange not being triggered from dispatched event
React onChange not being triggered from dispatched event

Time:10-17

I am trying to trigger onChange for a textarea by calling dispatchEvent on a ref that gets passed to the textarea.

The textarea:

<textarea
    onChange={handleTextAreaChange}
    className={`${classes['text-input']}${
        error && touched ? ` ${classes.error}` : ''
    }`}
    ref={textAreaRef as MutableRefObject<HTMLTextAreaElement>}
    rows={numberOfRows}
    cols={numberOfCols}
    onBlur={onBlur}
    id={id}
    value={content}
></textarea>

The code firing the event:

const changeEvent = new InputEvent('change', { bubbles: true });

textAreaRef.current?.dispatchEvent(changeEvent);

I have tried both input and change as the event types used for the event and neither have been caught by onChange. I know both from debugging and the behavior of my code that textAreaRef.current is defined, so that can't be what's causing onChange not to get called.

Why aren't the events I'm dispatching getting caught by onChange?

CodePudding user response:

As per the comment, the right way to achieve what you want is not to trigger events but to manipulate the Formik store. It would be very opaque to attempt to do this by programmatically calling events and using element refs to do manual DOM calls like this is generally seen as a last-ditch desperate escape hatch.

If you are looking to set the value based on some other action, just call setFieldValue from formik. You can get this from context (or render props, or useForm if you do it that way instead of <Formik> -- there are many ways):

Change yourFieldName to the formik name for this field that represents where it is in the state. And of course, you need to impl getBoldText.

import { useFormikContext } from 'formik'

// ...

const { values, setFieldValue } = useFormikContext()

// ...

<button onClick={() => setFieldValue('yourFieldName', getBoldText(values.yourFieldName))}>Bold text</button>
  • Related