Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open link in new tab in react router programmatically

I am using ReactJS for a project along with React Router (no redux) I want to programmatically open a link but on a new tab. I am aware that using onClickNode={e => this.props.history.push('/${e.data.node.id}')} I can go to the desired link but the problem is that it gets opened in the same tab. Also there is no way to use JSX in that function and hence no possibility of adding <Link> component.

( I am using React Router v4)

like image 526
Aron Karmer Avatar asked Dec 13 '17 09:12

Aron Karmer


People also ask

How do I open a link in a new tab with react?

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. Copied!

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.

How do I open the react component in a new window?

To open a component in new window on a click in React, we can call window. open with the element we created. to create the RenderInWindow component that opens a new window when it mounts. To do this, we create the container state with useState .

How redirect external URL in react?

Use the window. location. replace() method to redirect to an external url in React, e.g. window. location.


2 Answers

This https://stackoverflow.com/a/11384018/7697399 answer helped me out and worked flawlessly. This could be done without the help of react-router.

function openInNewTab(url) {   var win = window.open(url, '_blank');   win.focus(); } 
like image 113
Aron Karmer Avatar answered Sep 20 '22 23:09

Aron Karmer


Similar to the previous answer, but doesn't error out if the window couldn't be opened.

function open(url) {   const win = window.open(url, '_blank');   if (win != null) {     win.focus();   } } 
like image 24
Ares Avatar answered Sep 22 '22 23:09

Ares