Skip to content

Instantly share code, notes, and snippets.

@project42da
Last active March 26, 2020 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save project42da/39e317a7682cfe8c1b8957f98ac2e16e to your computer and use it in GitHub Desktop.
Save project42da/39e317a7682cfe8c1b8957f98ac2e16e to your computer and use it in GitHub Desktop.
react-router NavButton
import React, { MouseEvent } from "react";
import { useRouteMatch, useHistory } from "react-router-dom";
import classnames from 'classnames';
type Props = {
to: string,
replace?: boolean,
exact: boolean,
className: string,
activeClassName: string,
children: any,
[propName: string]: any
}
const NavButton = ({
to,
replace,
exact,
className,
activeClassName,
children,
...props
}: Props) => {
const match = useRouteMatch({
path: to,
exact
});
const history = useHistory();
const navigate = () => {
const method = replace ? history.replace : history.push;
method(to);
}
const handleClick = (e: MouseEvent) => {
e.preventDefault();
navigate();
}
return (
<button
{...props}
onClick={handleClick}
className={classnames(className,{[activeClassName]: match})}
>{children}</button>
);
}
export default NavButton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment