Skip to content

Instantly share code, notes, and snippets.

@project42da project42da/NavButton.tsx
Last active Mar 26, 2020

Embed
What would you like to do?
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
You can’t perform that action at this time.