React-router: Open Link in new tab (target="_blank")

Created on 7 Oct 2015  Â·  7Comments  Â·  Source: ReactTraining/react-router

I see in issue #1510 you guys don't think opening Links in a new tab should be supported by react-router but I think I have an argument for why it should.

One nice thing about Link is it's one consistent way across my codebase where I link to my other routes. I can build other abstractions on top of it (PostLink, UserLink) and use those throughout. Without the target="_blank" prop on Link, I have to use the this.props.history.createHref API which means rebuilding all of those abstractions rather than just passing an additional prop in.

// Preferred
<Link to="myRoute" params={myParams} target="_blank">

// More work, less consistency to do effectively the same thing
var href = this.props.history.createHref('myRoute', myParams);
<a href={href} target="_blank">

// Manual and awful (if anything ever changes)
var href = '/myRoute/' + myParams.foo + '/' + myParams.bar;
<a href={href} target="_blank">

As you can see the first one really just makes my life so much better because I don't have to use the history API. What are your thoughts on adding this prop?

Most helpful comment

In 1.0 this is supported. We just pass all extra props you give your <Link> through to the <a> element. So, <Link ... target="_blank"> will work as you'd expect.

All 7 comments

In 1.0 this is supported. We just pass all extra props you give your <Link> through to the <a> element. So, <Link ... target="_blank"> will work as you'd expect.

Amazing! I'll add a comment to the other issue. Thanks :)

@mjackson The target="_blank" is indeed passed on as expected (1.0.0-rc1), but the onClick handler calls event.preventDefault() and handles the transition itself with this.context.history.pushState(…), i.e. no new page is opened.

I think in order to enable the expected behavior, handleClick would have to check the target prop and if set to "_blank" not call event.preventDefault() unless allowTransition is set to false.

In order to better illustrate what I mean, I created a pull request.

Excellent point, @sgoll. Thank you for bringing that up.

This feature was added in #2193

One issue I have had when using target="_blank" is that state in the to prop does not seem to carry over.

This works without any issue:

<Label
  icon="external"
  color="teal"
  content="Knowledgebase"
  as={Link}
  to={{
    pathname: '/app/variant-knowledgebase/',
    state: { variant: get(variantCall, 'variant.id') }
   }}
/>

the moment I add target="_blank", state is null in the new tab that is opened.

<Label
  icon="external"
  color="teal"
  content="Knowledgebase"
  as={Link}
  target="_blank"
  to={{
    pathname: '/app/variant-knowledgebase/',
    state: { variant: get(variantCall, 'variant.id') }
   }}
/>

Is this expected behavior?

Was this page helpful?
0 / 5 - 0 ratings