Link.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * React Static Boilerplate
  3. * https://github.com/koistya/react-static-boilerplate
  4. * Copyright (c) Konstantin Tarkus (@koistya) | MIT license
  5. */
  6. import React, { Component, PropTypes } from 'react';
  7. import './Link.scss';
  8. import Location from '../../core/Location';
  9. function isLeftClickEvent(event) {
  10. return event.button === 0;
  11. }
  12. function isModifiedEvent(event) {
  13. return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
  14. }
  15. class Link extends Component {
  16. static propTypes = {
  17. to: PropTypes.string.isRequired,
  18. children: PropTypes.element.isRequired,
  19. state: PropTypes.object,
  20. onClick: PropTypes.func,
  21. };
  22. static handleClick = event => {
  23. let allowTransition = true;
  24. let clickResult;
  25. if (this.props && this.props.onClick) {
  26. clickResult = this.props.onClick(event);
  27. }
  28. if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
  29. return;
  30. }
  31. if (clickResult === false || event.defaultPrevented === true) {
  32. allowTransition = false;
  33. }
  34. event.preventDefault();
  35. if (allowTransition) {
  36. const link = event.currentTarget;
  37. Location.pushState(
  38. this.props && this.props.state || null,
  39. this.props && this.props.to || (link.pathname + link.search));
  40. }
  41. };
  42. render() {
  43. const { to, children, ...props } = this.props;
  44. return <a {...props} onClick={Link.handleClick.bind(this)}>{children}</a>;
  45. }
  46. }
  47. export default Link;