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

Make to prop on Link optional again #5271

Closed
wants to merge 2 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
1 change: 1 addition & 0 deletions packages/react-router-dom/docs/api/Link.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Provides declarative, accessible navigation around your application.
import { Link } from 'react-router-dom'

<Link to="/about">About</Link>
<Link>Disabled</Link> // renders <a> without a href attribute
```

## to: string
Expand Down
6 changes: 5 additions & 1 deletion packages/react-router-dom/modules/Link.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Link extends React.Component {
to: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
]).isRequired
])
}

static defaultProps = {
Expand Down Expand Up @@ -58,6 +58,10 @@ class Link extends React.Component {
render() {
const { replace, to, innerRef, ...props } = this.props // eslint-disable-line no-unused-vars

if (to == null) {
return <a {...props} href={null} />
}

const href = this.context.router.history.createHref(
typeof to === 'string' ? { pathname: to } : to
)
Expand Down
44 changes: 44 additions & 0 deletions packages/react-router-dom/modules/__tests__/Link-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,50 @@ describe('A <Link>', () => {
expect(href).toEqual('/the/path?the=query#the-hash')
})

describe('when the "to" prop is unspecified', () => {
it('returns an anchor tag without a href', () => {
const node = document.createElement('div')

ReactDOM.render((
<MemoryRouter>
<Link>link</Link>
</MemoryRouter>
), node)

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

expect(href).toEqual(null)
})

it('omits href prop', () => {
const node = document.createElement('div')

ReactDOM.render((
<MemoryRouter>
<Link href="/path">link</Link>
</MemoryRouter>
), node)

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

expect(href).toEqual(null)
})

it('passes down other props', () => {
const node = document.createElement('div')

ReactDOM.render((
<MemoryRouter>
<Link className="link-class">link</Link>
</MemoryRouter>
), node)

const className = node.querySelector('a').getAttribute('class')

expect(className).toEqual('link-class')
})
})

it('exposes its ref via an innerRef prop', done => {
const node = document.createElement('div')

Expand Down