From c43fb617fbdcf0fcaa5f0aeb4488cec1e7cec779 Mon Sep 17 00:00:00 2001 From: Michael Jackson Date: Wed, 7 Oct 2015 17:08:24 -0700 Subject: [PATCH] [added] prop Fixes #2176 --- docs/API.md | 5 ++++- modules/Link.js | 18 +++++++++++------- modules/__tests__/Link-test.js | 4 ++-- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/docs/API.md b/docs/API.md index fff28fd2e9..278dd846d3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -85,11 +85,14 @@ A `` also knows when the route it links to is active and automatically app #### Props ##### `to` -The path to link to, e.g., `/users/123`. +The path to link to, e.g. `/users/123`. ##### `query` An object of key:value pairs to be stringified. +##### `hash` +A hash to put in the URL, e.g. `#a-hash`. + ##### `state` State to persist to the `location`. diff --git a/modules/Link.js b/modules/Link.js index 4ad03cf11a..eb762b3099 100644 --- a/modules/Link.js +++ b/modules/Link.js @@ -43,12 +43,13 @@ class Link extends React.Component { } static propTypes = { - activeStyle: object, - activeClassName: string, - onlyActiveOnIndex: bool.isRequired, to: string.isRequired, query: object, + hash: string, state: object, + activeStyle: object, + activeClassName: string, + onlyActiveOnIndex: bool.isRequired, onClick: func } @@ -77,16 +78,19 @@ class Link extends React.Component { } render() { - const { history } = this.context - const { activeClassName, activeStyle, onlyActiveOnIndex, to, query, state, onClick, ...props } = this.props + const { to, query, hash, state, activeClassName, activeStyle, onlyActiveOnIndex, ...props } = this.props + // Manually override onClick. props.onClick = (e) => this.handleClick(e) - // Ignore if rendered outside the context - // of history, simplifies unit testing. + // Ignore if rendered outside the context of history, simplifies unit testing. + const { history } = this.context if (history) { props.href = history.createHref(to, query) + if (hash) + props.href += hash + if (activeClassName || (activeStyle != null && !isEmptyObject(activeStyle))) { if (history.isActive(to, query, onlyActiveOnIndex)) { if (activeClassName) diff --git a/modules/__tests__/Link-test.js b/modules/__tests__/Link-test.js index 4752192b4c..e328398b55 100644 --- a/modules/__tests__/Link-test.js +++ b/modules/__tests__/Link-test.js @@ -33,7 +33,7 @@ describe('A ', function () { it('knows how to make its href', function () { class LinkWrapper extends React.Component { render() { - return Link + return Link } } @@ -43,7 +43,7 @@ describe('A ', function () { ), node, function () { const a = node.querySelector('a') - expect(a.getAttribute('href')).toEqual('/hello/michael?the=query') + expect(a.getAttribute('href')).toEqual('/hello/michael?the=query#the-hash') }) })