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)
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!
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.
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 .
Use the window. location. replace() method to redirect to an external url in React, e.g. window. location.
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(); }
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With