React

All you need to know about React Router Dom Link

Link

React Router Dom Link is the component through which you can add menu navigation to your react application.

Here is a very simple React Router Dom Link example.

<Link to="/contact">Contact Us</Link>

You can pass query parameters to the to attribute of React Router Dom Link component. In below example we are passing name query parameter with value as ShinChan.

<Link to="/greetings?name=ShinChan"/>

You can also pass an object to the to attribute of Link component.

<Link
  to={{
    pathname: "/subjects",
    search: "?sort=score",
    hash: "#choco",
    state: { fromWorkspace: true }
  }}
/>

Here the object has 4 properties

  • pathname – Here we specify path parameters.
  • search – Here we specify query parameters.
  • hash – It is used if you want to specify hash which will be added to url, this is generally used in legacy browsers.
  • state – It is used for state persisting to location.

Please note that search, hash and state properties are deprecated now and could be removed in future releases. I would recommend you use the string option instead of object option while specifying to attribute of React Router Dom Link.

React Router Dom Link onClick

There are use cases where you want to do something specific when a user clicks on React Router Dom Link. You can just put your function on the onClick attribute. Below is a simple React Router Dom Link onClick example.

<Link to="about" onClick={onAboutClick}>Here</Link>

function omAboutClick(e) {
  /* call this if you want to prevent default behavior, that is transition to fire */
  e.preventDefault();
}

React Router Dom Link Style

There are two properties through which you can style your React router dom Link. You can specify activeClassName property. As the name specifies, this class is applied when Link’s route is active. If you want to directly apply a style when Link’s route is active, then use the activeStyle property.

React Router Dom Link Disable

If you want to disable a Link in React Router, then use the CSS pointer-events attribute. Here is a simple example on how to disable a React Router Dom Link.

// JSX 
<Link to='/hangover' className='disable-link'>Bar</Link>
// CSS
.disable-link {
  pointer-events: none;
}

React Router Dom Link Open New Tab

If you have a requirement of opening a new tab on clicking the React Router Dom Link, then just use target attribute and specify _blank. See the example below for reference.

<Link to="/service" target="_blank" >Services</Link>

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tagged ,

Leave a Reply

Your email address will not be published. Required fields are marked *