Handle an event and non-event function in the same way?


I want to have a function that takes a path and navigates to it. I'd like it to be universally usable. Like this:

export const navigate = (path: string) => {
 getHistory().push(path)
}

So, I want to be able to call it as a normal function

navigate('gohere')

as well as in response to an onClick action

onClick={navigate('gohere')

Unfortunately, that second one doesn't work. If I add the event in like this:

export const clicknavigate = (path: string) => (event: any) => {
    getHistory().push(path)
}

then it works, but that means I have to have two functions for every action - one if it is called from a click or mouse event, and one if not.

There has to be a way to handle both with a single function?

- - Source

Answers

answered 5 day ago Helmer Barcos #1

What about

export const clicknavigate = (path: string, event: any) => {
    if(event){
      getHistory().push(path)
    }
    return         
}

then call it on your onClick method as follow onClick={(e) => clicknavigate('gohere', e)}

comments powered by Disqus