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

Relative <Route> and <Link> #4355

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions packages/react-router-dom/modules/Link.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { PropTypes } from 'react'
import { resolveLocation } from 'react-router/resolve'

const isModifiedEvent = (event) =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
Expand All @@ -7,11 +8,15 @@ const isModifiedEvent = (event) =>
* The public API for rendering a router-aware <a>.
*/
class Link extends React.Component {

static contextTypes = {
router: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
createHref: PropTypes.func.isRequired
createHref: PropTypes.func.isRequired,
match: PropTypes.shape({
url: PropTypes.string
})
}).isRequired
}

Expand Down Expand Up @@ -42,8 +47,8 @@ class Link extends React.Component {
event.preventDefault()

const { router } = this.context
const { replace, to } = this.props

const { replace } = this.props
const to = this.absolutePathname()
if (replace) {
router.replace(to)
} else {
Expand All @@ -52,11 +57,28 @@ class Link extends React.Component {
}
}

absolutePathname() {
const { to } = this.props
const { match } = this.context.router
const base = (match && match.url) ? match.url : ''
return resolveLocation(to, base)
}

componentWillMount() {
const { router } = this.context
this.unlisten = router.listen(() => this.forceUpdate())
}

componentWillUnmount() {
this.unlisten()
}

render() {
const { router } = this.context
const { replace, to, ...props } = this.props // eslint-disable-line no-unused-vars

const href = this.context.router.createHref(
typeof to === 'string' ? { pathname: to } : to
const absoluteTo = this.absolutePathname()
const href = router.createHref(
typeof absoluteTo === 'string' ? { pathname: absoluteTo } : absoluteTo
)

return <a {...props} onClick={this.handleClick} href={href}/>
Expand Down
90 changes: 90 additions & 0 deletions packages/react-router-dom/modules/__tests__/Link-test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import expect from 'expect'
import React from 'react'
import ReactDOM from 'react-dom'
import { Simulate } from 'react-addons-test-utils'
import MemoryRouter from 'react-router/MemoryRouter'
import Route from 'react-router/Route'
import Switch from 'react-router/Switch'
import HashRouter from '../HashRouter'
import Link from '../Link'

Expand Down Expand Up @@ -89,3 +92,90 @@ describe('A <Link> underneath a <HashRouter>', () => {
})
})
})

describe('A <Link> with a relative to', () => {
const node = document.createElement('div')

afterEach(() => {
ReactDOM.unmountComponentAtNode(node)
})

it('resolves using the parent match', () => {
const initialEntries = ['/', '/recipes']
ReactDOM.render((
<MemoryRouter initialEntries={initialEntries} initialIndex={1}>
<Route path='/recipes' render={() => (
<Link to='tacos'>Chess</Link>
)} />
</MemoryRouter>
), node)
const a = node.getElementsByTagName('a')[0]
expect(a.pathname).toBe('/recipes/tacos')
})

it('works when not in a route', () => {
const initialEntries = ['/']
ReactDOM.render((
<MemoryRouter initialEntries={initialEntries} initialIndex={0}>
<Link to='recipes'>Recipes</Link>
</MemoryRouter>
), node)
const a = node.getElementsByTagName('a')[0]
expect(a.pathname).toBe('/recipes')
})

it('navigates correctly', () => {
const initialEntries = ['/', '/recipes']
const RESTAURANTS = 'RESTAURANTS'
ReactDOM.render((
<MemoryRouter initialEntries={initialEntries} initialIndex={1}>
<Switch>
<Route path='/recipes' render={() => (
<Link to='../restaurants'>Order Takeout</Link>
)} />
<Route path='/restaurants' render={() => (
<div>{RESTAURANTS}</div>
)} />
</Switch>
</MemoryRouter>
), node)
expect(node.textContent).toNotContain(RESTAURANTS)
const a = node.getElementsByTagName('a')[0]
Simulate.click(a, {
defaultPrevented: false,
preventDefault() { this.defaultPrevented = true },
metaKey: null,
altKey: null,
ctrlKey: null,
shiftKey: null,
button: 0
})
expect(node.textContent).toContain(RESTAURANTS)
})

it('updates regardless of sCU blocks', () => {
let goForward
class UpdateBlocker extends React.Component {
shouldComponentUpdate() {
return false
}
render() {
goForward = this.props.goForward
return <Link to='store' />
}
}

ReactDOM.render((
<MemoryRouter initialEntries={[ '/bubblegum', '/shoelaces' ]}>
<Route path='/:store' component={UpdateBlocker}/>
</MemoryRouter>
), node)

let href = node.querySelector('a').getAttribute('href')
expect(href).toEqual('/bubblegum/store')
goForward()

href = node.querySelector('a').getAttribute('href')
expect(href).toEqual('/shoelaces/store')
})
})
41 changes: 37 additions & 4 deletions packages/react-router-website/modules/components/ExampleRouter.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,40 @@
import React from 'react'
import React, { PropTypes } from 'react'

const ExampleRouter = ({ children }) => (
children ? React.Children.only(children) : null
)
class ExampleRouter extends React.Component {

static contextTypes = {
router: PropTypes.object.isRequired
}

static childContextTypes = {
router: PropTypes.object.isRequired
}

getChildContext() {
return {
router: this.router
}
}

componentWillMount() {
this.router = {
...this.context.router,
match: null
}

this.unlisten = this.router.listen(() => {
this.router.location = this.context.router.location
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to modify <ExampleRouter> in order for it to work with relative routes. The <FakeBrowser> renders everything inside of a pathless <Route>, so without this relative <Route>s and <Link>s would resolve using that <Route>'s match. This just sets the <ExampleRouter>'s match to null. It also has to listen for location changes because any of its children that listen for location changes would be re-rendering via the listener prior to <ExampleRouter>'s getChildContext being called on navigation.

})
}

componentWillUnmount() {
this.unlisten()
}

render() {
const { children } = this.props
return children ? React.Children.only(children) : null
}
}

export default ExampleRouter
13 changes: 9 additions & 4 deletions packages/react-router/modules/Redirect.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { PropTypes } from 'react'
import { resolveLocation } from './resolve'

/**
* The public API for updating the location programatically
Expand All @@ -9,7 +10,10 @@ class Redirect extends React.Component {
router: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
staticContext: PropTypes.object
staticContext: PropTypes.object,
match: PropTypes.shape({
url: PropTypes.string
})
}).isRequired
}

Expand Down Expand Up @@ -38,11 +42,12 @@ class Redirect extends React.Component {
perform() {
const { router } = this.context
const { push, to } = this.props

const { match } = router
const loc = resolveLocation(to, match && match.url ? match.url : '')
if (push) {
router.push(to)
router.push(loc)
} else {
router.replace(to)
router.replace(loc)
}
}

Expand Down
12 changes: 9 additions & 3 deletions packages/react-router/modules/Route.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import React, { PropTypes } from 'react'
import matchPath from './matchPath'

const computeMatch = (router, { computedMatch, path, exact, strict }) =>
computedMatch || matchPath(router.location.pathname, path, { exact, strict })
computedMatch || matchPath(
router.location.pathname,
path,
{ exact, strict },
router.match
)

/**
* The public API for matching a single path and rendering.
Expand Down Expand Up @@ -51,7 +56,8 @@ class Route extends React.Component {

static contextTypes = {
router: PropTypes.shape({
listen: PropTypes.func.isRequired
listen: PropTypes.func.isRequired,
match: PropTypes.object
}).isRequired
}

Expand Down Expand Up @@ -98,7 +104,7 @@ class Route extends React.Component {

componentWillReceiveProps(nextProps) {
Object.assign(this.router, {
match: computeMatch(this.router, nextProps)
match: computeMatch(this.context.router, nextProps)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to use the parent router object, not this.router in order to have access to the parent match.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change makes me nervous. If it's needed here, it feels like the kind of thing that should be needed more generally. If it's not needed outside the context of this PR, it's probably going to cause a bug.

})
}

Expand Down
13 changes: 10 additions & 3 deletions packages/react-router/modules/Switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import matchPath from './matchPath'
class Switch extends React.Component {
static contextTypes = {
router: PropTypes.shape({
listen: PropTypes.func.isRequired
listen: PropTypes.func.isRequired,
match: PropTypes.object
}).isRequired
}

Expand Down Expand Up @@ -41,12 +42,18 @@ class Switch extends React.Component {
render() {
const { children } = this.props
const { location } = this.state
const routes = React.Children.toArray(children)
const { match:parentMatch } = this.context.router

const routes = React.Children.toArray(children)
let route, match
for (let i = 0, length = routes.length; match == null && i < length; ++i) {
route = routes[i]
match = matchPath(location.pathname, route.props.path, route.props)
match = matchPath(
location.pathname,
route.props.path,
route.props,
parentMatch
)
}

return match ? React.cloneElement(route, { computedMatch: match }) : null
Expand Down
34 changes: 34 additions & 0 deletions packages/react-router/modules/__tests__/Redirect-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import expect from 'expect'
import React from 'react'
import ReactDOM from 'react-dom'
import createMemoryHistory from 'history/createMemoryHistory'
import Router from '../Router'
import Redirect from '../Redirect'

describe('Redirect', () => {
const createHistoryMock = () => {
const pushes = []
const replaces = []
const history = createMemoryHistory()
history.push = (loc) => pushes.push(loc)
history.replace = (loc) => replaces.push(loc)
history.getResults = () => ({ replaces, pushes })
return history
}

it('works with relative paths', () => {
const div = document.createElement('div')
const REDIRECTED = 'REDIRECTED'
const history = createHistoryMock()
ReactDOM.render((
<Router history={history}>
<Redirect to={REDIRECTED} push={true}/>
</Router>
), div, () => {
const { pushes, replaces } = history.getResults()
expect(pushes.length).toEqual(1)
expect(pushes[0]).toEqual('/' + REDIRECTED)
expect(replaces.length).toEqual(0)
})
})
})
Loading