joy08
joy08

Reputation: 9662

Want to simultaneously open a URL on the next tab and also navigate to a route: React+ React Router V4+ semantic-ui-react

I am having this scenario where in I fetch a particular URL from backend and then on click of a button , I have to open that link in a new tab and also load a component in the current tab using react-router


import { Button } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import * as React from 'react';

this.state={ url: ''} ; // This url I am able to get using fetch

//I get URL from the backend, and then I am trying to set it to href attribute. Routing just works find but link does not get opened in the new tab.

<Link to="/path">
     <a href={this.state.url} target="_blank">
        <Button size="small" fluid >
           Continue
        </Button>
     </a>
</Link>

Upvotes: 0

Views: 1004

Answers (2)

gk0r
gk0r

Reputation: 606

Disclaimer. This is for those who came across this answer on Google and did not like the suggested implementation.

A better solution (in my opinion) is this

<Button as={Link} to='/path' target='_blank'>

Upvotes: 0

Mezbaul
Mezbaul

Reputation: 1272

try this:

onBtnClick = (e) => {
    window.open(this.state.url, '_blank');
    this.props.history.push('/link/to/route/in/current/tab');
}

...

<Button size="small" fluid onClick={this.onBtnClick}>
    Continue
</Button>

Upvotes: 2

Related Questions