Skip to content

Commit 0676d61

Browse files
committed
Add support for "to" prop as a function
1 parent ca6f129 commit 0676d61

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
"react": "^15.5.4",
7676
"react-bootstrap": "^0.30.9",
7777
"react-dom": "^15.5.4",
78-
"react-router": "^2.6.0",
78+
"react-router": "^3.0.5",
7979
"release-script": "^1.0.2",
8080
"rimraf": "^2.6.1",
8181
"shelljs": "^0.7.7",

src/LinkContainer.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,16 @@ function createLocationDescriptor(to, query, hash, state) {
2323
return to;
2424
}
2525

26+
function resolveToLocation(to, router) {
27+
return typeof to === 'function' ? to(router.location) : to;
28+
}
29+
2630
const propTypes = {
2731
onlyActiveOnIndex: PropTypes.bool.isRequired,
2832
to: PropTypes.oneOfType([
2933
PropTypes.string,
3034
PropTypes.object,
35+
PropTypes.func,
3136
]).isRequired,
3237
query: PropTypes.string,
3338
hash: PropTypes.string,
@@ -84,15 +89,16 @@ class LinkContainer extends React.Component {
8489
render() {
8590
const { router } = this.context;
8691
const { onlyActiveOnIndex, to, children, ...props } = this.props;
92+
const toLocation = resolveToLocation(to, router);
8793

8894
props.onClick = this.onClick;
8995

9096
// Ignore if rendered outside Router context; simplifies unit testing.
9197
if (router) {
92-
props.href = router.createHref(to);
98+
props.href = router.createHref(toLocation);
9399

94100
if (props.active == null) {
95-
props.active = router.isActive(to, onlyActiveOnIndex);
101+
props.active = router.isActive(toLocation, onlyActiveOnIndex);
96102
}
97103
}
98104

test/LinkContainer.spec.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,31 @@ describe('LinkContainer', () => {
4242
expect(anchor.getAttribute('href')).to.equal('/foo?bar=baz#the-hash');
4343
});
4444

45+
it('should support "to" prop as a function', () => {
46+
const router = ReactTestUtils.renderIntoDocument(
47+
<Router history={createMemoryHistory('/foo')}>
48+
<Route
49+
path="/foo"
50+
component={() => (
51+
<LinkContainer
52+
to={location => ({
53+
...location,
54+
query: { bar: 'baz' },
55+
})}
56+
>
57+
<Component>Foo</Component>
58+
</LinkContainer>
59+
)}
60+
/>
61+
</Router>
62+
);
63+
64+
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(
65+
router, 'A'
66+
);
67+
expect(anchor.getAttribute('href')).to.equal('/foo?bar=baz');
68+
});
69+
4570
it('should not add extra DOM nodes', () => {
4671
const router = ReactTestUtils.renderIntoDocument(
4772
<Router history={createMemoryHistory('/')}>

0 commit comments

Comments
 (0)