UNPKG

1.61 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import classNames from 'classnames';
4import { mapToCssModules, tagPropType } from './utils';
5
6const propTypes = {
7 /** Add active class to NavLink */
8 active: PropTypes.bool,
9 /** Add custom class */
10 className: PropTypes.string,
11 /** Change underlying component's CSS base class name */
12 cssModule: PropTypes.object,
13 /** Disable the link */
14 disabled: PropTypes.bool,
15 href: PropTypes.any,
16 innerRef: PropTypes.oneOfType([
17 PropTypes.object,
18 PropTypes.func,
19 PropTypes.string,
20 ]),
21 /** Function to be triggered on click */
22 onClick: PropTypes.func,
23 /** Set a custom element for this component */
24 tag: tagPropType,
25};
26
27class NavLink extends React.Component {
28 constructor(props) {
29 super(props);
30
31 this.onClick = this.onClick.bind(this);
32 }
33
34 onClick(e) {
35 if (this.props.disabled) {
36 e.preventDefault();
37 return;
38 }
39
40 if (this.props.href === '#') {
41 e.preventDefault();
42 }
43
44 if (this.props.onClick) {
45 this.props.onClick(e);
46 }
47 }
48
49 render() {
50 let {
51 className,
52 cssModule,
53 active,
54 tag: Tag = 'a',
55 innerRef,
56 ...attributes
57 } = this.props;
58
59 const classes = mapToCssModules(
60 classNames(className, 'nav-link', {
61 disabled: attributes.disabled,
62 active: active,
63 }),
64 cssModule,
65 );
66
67 return (
68 <Tag
69 {...attributes}
70 ref={innerRef}
71 onClick={this.onClick}
72 className={classes}
73 />
74 );
75 }
76}
77
78NavLink.propTypes = propTypes;
79
80export default NavLink;