I have a Link
:
<Link href={href} passHref shallow>
<StyledLink
$active={active}
$disabled={disabled}
onClick={() => passBackNumber(number)}
>
{number}
</StyledLink>
</Link>
where StyledLink
is my styled.a
element and onClick
passes number that was just clicked. I found information that if you want to use <Link/>
+ styled-components
you need to use passHref
. But issue is even though I specified shallow
, page still is getting refreshed. I only want to url to change and trigger callback. What did I do wrong?
The way I handle this type of implementation is to use the Extended Styles feature of styled-components. I make a styled-component that is tied to Next's <Link>
:
const StyledLink = styled(Link)`
align-items: center;
display: flex;
justify-content: space-between;
a, a:focus, a:visited, a:hover {
color: black;
text-decoration: none;
}
`
In the render function, I will apply the onClick
event directly into the nested <a>
tag like this:
<StyledLink href="#">
<a onClick={ () => passBackNumber(number) }>
</StyledLink>
Depending on what version of Next you're using, you may not need passHref
or shallow
anymore. Next 12.1+ with Webpack 5+ can now leverage Rust-native compiling server-side with swc
& styled-components (more here).