forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLink.js
More file actions
109 lines (93 loc) · 2.66 KB
/
Link.js
File metadata and controls
109 lines (93 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import React, { Component, PropTypes } from 'react';
import * as RouterPropTypes from './PropTypes';
import { stringifyQuery } from './QueryUtils';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* <Link> components are used to create an <a> element that links to a route.
* When that route is active, the link gets an "active" class name (or the
* value of its `activeClassName` prop).
*
* For example, assuming you have the following route:
*
* <Route name="showPost" path="/posts/:postID" handler={Post}/>
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along query string parameters
* using the `query` prop.
*
* <Link to="/posts/123" query={{ show: true }}/>
*/
export default class Link extends Component {
static contextTypes = {
router: RouterPropTypes.router
}
static propTypes = {
activeStyle: PropTypes.object,
activeClassName: PropTypes.string,
to: PropTypes.string.isRequired,
query: PropTypes.object,
state: PropTypes.object,
onClick: PropTypes.func
}
static defaultProps = {
className: '',
activeClassName: 'active',
style: {}
}
handleClick = event => {
const { onClick, to, query, state } = this.props;
const { router } = this.context;
let allowTransition = true;
let clickResult;
if (this.props.onClick) {
clickResult = onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (clickResult === false || event.defaultPrevented === true) {
allowTransition = false;
}
event.preventDefault();
if (allowTransition) {
router.transitionTo(to, query, state);
}
}
createHref(pathname, query) {
const { router } = this.context;
return router.createHref(pathname, query);
}
render() {
const { router } = this.context;
const props = {
...this.props,
onClick: this.handleClick
};
// Ignore if rendered outside of the context of a router, simplifies
// unit testing.
if (router) {
const { to, query } = this.props;
props.href = this.createHref(to, query);
if (router.isActive(to, query)) {
if (props.activeClassName) {
props.className += props.className !== '' ? ` ${props.activeClassName}` : props.activeClassName;
}
if (props.activeStyle) {
props.style = {
...props.style,
...props.activeStyle
};
}
}
}
return <a {...props} />;
}
}