Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix <Link to="string"> #5489

Merged
merged 3 commits into from
Oct 3, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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