forked from react-navigation/react-navigation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLink.js
More file actions
61 lines (56 loc) · 1.73 KB
/
Copy pathLink.js
File metadata and controls
61 lines (56 loc) · 1.73 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
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { NavigationActions } from 'react-navigation';
const isModifiedEvent = event =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
const Linkable = Inner => {
class LinkableWrapped extends Component {
render() {
return (
<Inner href={this.getURL()} onClick={this.onClick} {...this.props} />
);
}
getAction = () => {
const { to, href } = this.props;
if (typeof to === 'string') {
return NavigationActions.navigate({ routeName: to });
} else if (typeof to === 'object' && typeof to.type === 'string') {
return to;
} else if (href) {
const match = href.match(/^\/(.*)/);
if (match) {
const pathParts = match[1].split('#');
const path = pathParts[0];
let params = {};
if (pathParts.length) {
params.hash = pathParts[1];
}
const action = this.context.getActionForPathAndParams(path, params);
return action;
}
return null;
}
};
onClick = e => {
const action = this.getAction();
if (!isModifiedEvent(e) && action) {
this.context.dispatch(action);
e.preventDefault();
}
};
getURL() {
const action = this.getAction();
if (!action) return '#';
return this.context.getURIForAction(action);
}
static contextTypes = {
dispatch: PropTypes.func.isRequired,
getURIForAction: PropTypes.func.isRequired,
getActionForPathAndParams: PropTypes.func.isRequired,
};
}
return LinkableWrapped;
};
const Link = Linkable(props => <a {...props} />);
Link.Linkable = Linkable;
export default Link;