Skip to content

Commit

Permalink
Fix <Link to="string"> (#5489)
Browse files Browse the repository at this point in the history
* Fix <Link to="string">

New implementation will parse the string to create an actual location object. This also means that a to string with no pathname will resolve using the current location.

The "href" value is also now stored in state, only recalculating it when the "to" prop changes.

* Determine href in render

* Style tweaks
  • Loading branch information
pshrmn authored and timdorr committed Oct 3, 2017
1 parent 6d28a2e commit be6fb6d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/react-router-dom/modules/Link.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react'
import PropTypes from 'prop-types'
import invariant from 'invariant'
import { createLocation } from 'history'

const isModifiedEvent = (event) =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
Expand Down Expand Up @@ -68,10 +69,10 @@ class Link extends React.Component {
'You should not use <Link> outside a <Router>'
)

const href = this.context.router.history.createHref(
typeof to === 'string' ? { pathname: to } : to
)
const { history } = this.context.router
const location = typeof to === 'string' ? createLocation(to, null, null, history.location) : to

const href = history.createHref(location)
return <a {...props} onClick={this.handleClick} href={href} ref={innerRef}/>
}
}
Expand Down
17 changes: 17 additions & 0 deletions packages/react-router-dom/modules/__tests__/Link-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ describe('A <Link>', () => {
expect(href).toEqual('/the/path?the=query#the-hash')
})

describe('to as a string', () => {
it('resolves to with no pathname using current location', () => {
const node = document.createElement('div')

ReactDOM.render((
<MemoryRouter initialEntries={[ '/somewhere' ]}>
<Link to='?rendersWithPathname=true'>link</Link>
</MemoryRouter>
), node)

const href = node.querySelector('a').getAttribute('href')

expect(href).toEqual('/somewhere?rendersWithPathname=true')
})
})

it('throws with no <Router>', () => {
const node = document.createElement('div')

Expand Down Expand Up @@ -73,6 +89,7 @@ describe('A <Link> underneath a <HashRouter>', () => {

afterEach(() => {
ReactDOM.unmountComponentAtNode(node)
window.history.replaceState(null, '', '#')
})

const createLinkNode = (hashType, to) => {
Expand Down

0 comments on commit be6fb6d

Please sign in to comment.