1

I do know about this: How to use onClick event on Link: ReactJS?
But it's from 3 years ago and some people suggested it's not working anymore.

<Link
     onClick={() => {
          openSB(!open);
     }}
     to="/login"
>
     Sign In
</Link>

Explanation of the code:
onClick calls a react hook that updates the state (true | false) hence the "!".

This what I tried doing and it seems to work like magic. Is there any problem doing it this way or should I be doing in a different way? I looked at the implementation of Link and it doesn't seem to be using onClick anywhere yet this still works. Might be because it's a <a> element under the hood. Not sure why this works and that's why I asked.
I also looked at the react-router documentation and couldn't find anything on this topic so any help would be appreciated.

Marios
  • 26,333
  • 8
  • 32
  • 52

1 Answers1

1

If you are not sure that using onClick on that link is a reliable way, you can create a wrapper component around the link and put the onClick on it. When you click, the click event will bubble up until your wrapper component so you can handle it. That way your wrapper element is responsible for handling this.

If you don't want to add a wrapper element, you could add the onMouseUp to the Link component and call openSB(!open); from there, that way onClick is untouched.

Daniel Kemeny
  • 640
  • 1
  • 5
  • 11