UNPKG

1.09 kBJavaScriptView Raw
1import React from 'react';
2import {pathFor,navigate,navigateToRoute} from 'lucid-router';
3
4function isLeftClickEvent(e) {
5 return e.button === 0;
6}
7
8function isModifiedEvent(e) {
9 return Boolean(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
10}
11
12export default class Link extends React.Component {
13 onClick = (e) => {
14 const {onClick, target} = this.props;
15 let allowTransition = true;
16
17 if (onClick instanceof Function)
18 onClick(e);
19
20 if (isModifiedEvent(e) || !isLeftClickEvent(e))
21 return;
22
23 if (e.defaultPrevented === true)
24 allowTransition = false;
25
26 if (target) {
27 if (!allowTransition)
28 e.preventDefault();
29
30 return;
31 }
32
33 if (allowTransition) {
34 const {to, params, href} = this.props;
35 if (to)
36 navigateToRoute(to, params, e);
37 else if (href != null)
38 navigate(href, e);
39 }
40 }
41
42 render () {
43 const {to, params, href, children, ...props} = this.props;
44 const linkTo = to ? pathFor(to, params) : href;
45 return <a {...props} href={linkTo} onClick={this.onClick}>{children}</a>;
46 }
47}