skip to Main Content

How can I know the events from onBeforeInput and onInput are related?

export const MyApp = () => {

    const onBeforeInput = (eventBefore) => {
        console.log(eventBefore)
    }

    const onInput = (event) => {
        console.log(event)

        const eventBefore = getEventBefore() // how can i get eventBefore here?
        console.log(eventBefore)
    }

    return (
        <textarea onBeforeInput={onBeforeInput} onInput={onInput}/>
    );
}

How can I use the associated eventBefore inside onInput?


Comment: I am asking because I need to use selectionStart from eventBefore inside onInput.

2

Answers


  1. Chosen as BEST ANSWER

    I have found that using onKeyDown is better then using onBeforeInput, since onBeforeInput does not trigger on backspace.


  2. Store the eventBefore in a variable common to both functions

    If you create the variable in an environment that encloses both functions, they should share a single variable:

    export const MyApp = () => {
    
        let theEventBefore = null
    
        const onBeforeInput = (eventBefore) => {
            theEventBefore = eventBefore
            console.log("theEventBefore being set to:",theEventBefore)
        }
    
        const onInput = (event) => {
            console.log(event)
            console.log("theEventBefore being read as:",theEventBefore)
    
        }
    
        return (
            <textarea onBeforeInput={onBeforeInput} onInput={onInput}/>
        );
    }
    
    

    beforeInput will finish before onInput starts, as long as beforeInput is synchronous

    Javascript is single-threaded, so unless you are using promises, or async/await, etc, you can be sure that beforeInput will complete first.

    Once the beforeinput event has completed, the browser will process the user input and then fire the input event.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search