2

I've asked the same question before but now it's not working with react-router v6.

I've simplified the question to how can I output to console when a <Link /> is clicked?

Link in side menu component

<Link to={"/entity"}>Entity</Link>

The route from the main app.js

<Routes>
    <Route path="/entity" element={<Entity />} />
</Routes>

How to perform an action once the link is clicked for a second time (the page is already showing) This example is just outputting to console whenever the <Link> is clicked, but the output only shows the first time it loads (or mounts)


function Entity(props) {

    console.log('link clicked');

    useEffect(() => {
        console.log('link clicked');
    });

}
Bradmage
  • 1,233
  • 1
  • 15
  • 41
  • Sorry, the use case is a bit fuzzy now. Does this fork of my sandbox from your other question do the trick? https://codesandbox.io/s/how-to-know-a-react-link-component-has-been-clicked-forked-jvrj0?file=/src/App.js – Drew Reese Nov 13 '21 at 07:19
  • Perfect, I dumped your app.js into my app and it worked as intended. I'll adapt my old code from that. There's not that many changes to make, but is just enough to stop it working. – Bradmage Nov 13 '21 at 21:57

2 Answers2

1

The main change from the previous solution to the new one is that RRDv6 doesn't have a Redirect component and the Link component API changed slightly, the route state is now a first-level prop instead of being nested on the to prop object.

Link

<Link
  onClick={() => setLinkKey(uuidV4())}
  key={linkKey}
  to={"/users"}
  state={{ key: linkKey }}
>
  Users
</Link>

The components rendered on that route still just look for the key to change when clicking that link again if already on the route.

Edit how-to-know-a-react-link-component-has-been-clicked (forked)

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
1

you can use onClicke like a prop in Link :

  <Link to={"/entity"}   onClick={()=>{
        console.log('link clicked');

         useEffect(() => {
                console.log('link clicked');
            });
}}>Entity</Link>
Samira
  • 2,361
  • 1
  • 12
  • 21