Bradmage
Bradmage

Reputation: 1231

React Router v6 onclick

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');
    });

}

Upvotes: 2

Views: 4437

Answers (2)

Samira
Samira

Reputation: 2733

you can use onClicke like a prop in Link :

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

         useEffect(() => {
                console.log('link clicked');
            });
}}>Entity</Link>

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202676

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)

Upvotes: 1

Related Questions