context.js
5 years ago
index.js
3 years ago
link.js
3 years ago
route.js
5 years ago
utils.js
5 years ago
link.js
44 lines
| 1 | const { useContext } = wp.element; |
| 2 | import { RouterContext, history } from "./context"; |
| 3 | import classNames from "classnames"; |
| 4 | import { match } from "path-to-regexp"; |
| 5 | |
| 6 | export function Link(props) { |
| 7 | const { to, onClick, children, activeClassName } = props; |
| 8 | const { route } = useContext(RouterContext); |
| 9 | |
| 10 | let state = { ...props }; |
| 11 | delete state.activeClassName; |
| 12 | |
| 13 | const isActive = () => { |
| 14 | const checkMatch = match(`${to}`); |
| 15 | return checkMatch(`${route.hash.substr(1)}`); |
| 16 | }; |
| 17 | |
| 18 | const handleClick = (e) => { |
| 19 | e.preventDefault(); |
| 20 | // Dont' navigate if current path |
| 21 | if (route.path === to) { |
| 22 | return; |
| 23 | } |
| 24 | // Trigger onClick prop manually |
| 25 | if (onClick) { |
| 26 | onClick(e); |
| 27 | } |
| 28 | const { search } = history.location; |
| 29 | |
| 30 | // Use history API to navigate page |
| 31 | history.push(`${search}#${to}`); |
| 32 | }; |
| 33 | |
| 34 | return ( |
| 35 | <a |
| 36 | {...state} |
| 37 | className={classNames({ [activeClassName]: isActive() }, props.className)} |
| 38 | onClick={handleClick} |
| 39 | > |
| 40 | {children} |
| 41 | </a> |
| 42 | ); |
| 43 | } |
| 44 |