-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add common commponent for AnchorLink and ButtonLink
- Loading branch information
1 parent
05f2e2a
commit 3071b33
Showing
1 changed file
with
86 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
import React, { type ReactNode, type ComponentProps } from 'react'; | ||
import { NavLink, useMatch, useNavigate } from 'react-router-dom'; | ||
|
||
import { css } from 'glamor'; | ||
|
||
import { type CSSProperties, styles } from '../../style'; | ||
|
||
import Button from './Button'; | ||
|
||
type ButtonLinkProps = ComponentProps<typeof Button> & { | ||
to: string; | ||
activeStyle?: CSSProperties; | ||
}; | ||
|
||
type AnchorLinkProps = { | ||
to: string; | ||
style?: CSSProperties; | ||
activeStyle?: CSSProperties; | ||
children?: ReactNode; | ||
}; | ||
|
||
const ButtonLink = ({ | ||
to, | ||
style, | ||
activeStyle, | ||
onClick, | ||
...props | ||
}: ButtonLinkProps) => { | ||
const navigate = useNavigate(); | ||
const match = useMatch({ path: to }); | ||
|
||
const handleClick = e => { | ||
onClick?.(e); | ||
navigate(to); | ||
}; | ||
|
||
return ( | ||
<Button | ||
style={{ | ||
...style, | ||
...(match ? activeStyle : {}), | ||
}} | ||
activeStyle={activeStyle} | ||
{...props} | ||
onClick={handleClick} | ||
/> | ||
); | ||
}; | ||
|
||
const AnchorLink = ({ to, style, activeStyle, children }: AnchorLinkProps) => { | ||
const match = useMatch({ path: to }); | ||
|
||
return ( | ||
<NavLink | ||
to={to} | ||
className={`${css([ | ||
styles.smallText, | ||
style, | ||
match ? activeStyle : null, | ||
])}`} | ||
> | ||
{children} | ||
</NavLink> | ||
); | ||
}; | ||
|
||
type LinkProps = { | ||
to: string; | ||
linkType?: 'button' | 'anchor'; | ||
style?: CSSProperties; | ||
activeStyle?: CSSProperties; | ||
children?: ReactNode; | ||
}; | ||
|
||
export default function Link({ linkType = 'anchor', ...props }: LinkProps) { | ||
switch (linkType) { | ||
case 'anchor': | ||
return <AnchorLink {...props} />; | ||
|
||
case 'button': | ||
return <ButtonLink {...props} />; | ||
|
||
default: | ||
return null; | ||
} | ||
} |