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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The onMouseUp solution is quite smart. I'll use that because I don't want to clutter the html with unnecessary divs.
I am glad that it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.