Monday, 31 July 2023

onChange prop and custom Event dispatch in React

I'm testing new version of my library tagger where there is custom Event dispatch on input element:

this._input.dispatchEvent(new Event('change', { bubbles: true }));

The problem is that onChange prop on that input is not triggered when custom event is triggered.

const App = () => {
    const [tags, setTags] = useState(null)
    const inputRef = useRef(null)

    // Write the Tagger code inside a useEffect hook
    // It will run when the component is initially rendered
    useEffect(() => {
        // Define the Tagger options
        const taggerOptions = {
            allow_spaces: true,
        }

        inputRef.current.addEventListener('change', (e) => {
            console.log(e);
        });

        // Initialize Tagger
        tagger(inputRef.current, taggerOptions)
    }, []);

    const onChange = (e) => {
        setTags(e.target.value)
    };

    return (
        <div className="app">
            <input type="text" ref={inputRef} onChange={onChange} defaultValue="charles, louis, michel" />

            {tags && <pre>{tags}</pre>}
        </div>
    )
}

in the above code, console.log is executed but setTags is not.

Is there a way to make custom change events on input be triggered on default event onChange={}?

If this is not possible I'm fine with an explanation why.

Is this documented somewhere that only native events can be used?

This is a CodePen demo where this can be tested.



from onChange prop and custom Event dispatch in React

No comments:

Post a Comment