Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React history.push allow user to open in new tab

Navigation between pages in my navbar is done using an onClick handler, rather than through hrefs. When doing this, I can't either middle click to open in a new tab or right click on the link and select open in new tab. I am using react-router-v4.

An example of a route.

<a onClick={() => this.props.history.push('/conference/')}>Conference</a>

Is there a way to allow this to happen in react or should I be using hrefs instead?

like image 975
Cameron Avatar asked Jun 16 '18 17:06

Cameron


People also ask

How do I open a new tab with push history?

If you simply want to open a new tab without any state transfer, you can just get the path using useHref hook (Docs). This is what the <Link> component internally uses. You can then open it in new tab using window.

How do you make a link open in a new tab in ReactJS?

To open a link in a new tab in React, use the <a> element and set its target prop to _blank , e.g. <a href="https://google.com" target="_blank" rel="noopener noreferrer"></a> . The _blank value means that the resource is loaded into a new tab.

How do you redirect to another tab in React JS?

Opening the link in a new tab To open the link in a new tab, we can use the <a> element by passing a target attribute with a value _blank . Note: If you are using target=_blank , your page performance may suffer to avoid that you can use rel="noreferrer noopener" . In programmatic navigation, we can use the window.


2 Answers

You can use <Link to='/conference'>Conference</Link> to do this.

like image 62
Rohith Murali Avatar answered Oct 24 '22 03:10

Rohith Murali


You should use Link from react router

<Link to={`/conference`}>Conference</Link>
like image 41
nishant Avatar answered Oct 24 '22 02:10

nishant