forked from react-bootstrap/react-router-bootstrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkContainer.js
107 lines (87 loc) · 2.2 KB
/
LinkContainer.js
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
// This is largely taken from react-router/lib/Link.
import PropTypes from 'prop-types';
import React from 'react';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(
event.metaKey ||
event.altKey ||
event.ctrlKey ||
event.shiftKey
);
}
function createLocationDescriptor(to, query, hash, state) {
if (query || hash || state) {
return { pathname: to, query, hash, state };
}
return to;
}
const propTypes = {
onlyActiveOnIndex: PropTypes.bool.isRequired,
to: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]).isRequired,
query: PropTypes.string,
hash: PropTypes.string,
state: PropTypes.object,
action: PropTypes.oneOf([
'push',
'replace',
]).isRequired,
onClick: PropTypes.func,
active: PropTypes.bool,
target: PropTypes.string,
children: PropTypes.node.isRequired,
};
const contextTypes = {
router: PropTypes.object,
};
const defaultProps = {
onlyActiveOnIndex: false,
action: 'push',
};
class LinkContainer extends React.Component {
onClick = (event) => {
const {
to, query, hash, state, children, onClick, target, action,
} = this.props;
if (children.props.onClick) {
children.props.onClick(event);
}
if (onClick) {
onClick(event);
}
if (
target ||
event.defaultPrevented ||
isModifiedEvent(event) ||
!isLeftClickEvent(event)
) {
return;
}
event.preventDefault();
this.context.router[action](
createLocationDescriptor(to, query, hash, state)
);
};
render() {
const { router } = this.context;
const { onlyActiveOnIndex, to, children, ...props } = this.props;
props.onClick = this.onClick;
// Ignore if rendered outside Router context; simplifies unit testing.
if (router) {
props.href = router.createHref(to);
if (props.active == null) {
props.active = router.isActive(to, onlyActiveOnIndex);
}
}
return React.cloneElement(React.Children.only(children), props);
}
}
LinkContainer.propTypes = propTypes;
LinkContainer.contextTypes = contextTypes;
LinkContainer.defaultProps = defaultProps;
export default LinkContainer;