Search code examples
htmlreactjshyperlinksingle-page-applicationsemantic-ui-react

How to implement "Open link in new tab" for links within Single Page React app


For navigation in my React App, I am using React Router DOM in combination with the History package.

This is an example of how navigation looks in the app:

navigateToAccount() {
  history.push('/account');
}

And in the render:

<Button content='My Account' onClick={this.navigateToAccount}/>
/*Button from Semantic UI React*/

So far this will just navigate the client to the "/account" page. The problem though is that there does not exist an option for right clicking to "Open in new tab". So, I tried fixing it by simply using the href tag like so:

<Button content='My Account' href='/account'/>

On the surface this looks to be working, We get the "Open link in new tab" when right clicking and a left click will navigate to the desired page. The problem with this approach is that it goes against the desired Single Page Application structure. When left-clicking on the button (therefore activating navigation to the href), it loads(reloads) the page from start. This means that the client will request the whole application(bundle.js) from the server again. This creates unnecessary load on the server and longer load times for the client.

My question is: Is there a way to enable "Open link in new tab" for a Link/Button without a page reload when left-clicking said Link/Button.


Solution

  • You can make use of Link component (from react-router-dom) which is essentially a wrapper around anchor tag and handles the reload stuff for you. You can wrap Button like this :-

    <Link to='/account'><Button content='My Account'/></Link>

    For more details, visit - https://reactrouter.com/web/api/Link