Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Features: useLinkClickHandler and useLinkPressHandler #7998

Merged
merged 3 commits into from Sep 3, 2021

Conversation

chaance
Copy link
Collaborator

@chaance chaance commented Sep 2, 2021

This PR adds two new APIs that simplify the creation of custom Link components:

  • useLinkClickHandler for react-router-dom
  • useLinkPressHandler for react-router-native

The idea is the same for each. There is a lot of logic in our onClick handler for the DOM link, and this hook provides a simple wrapper that consumers can use to capture all of that logic while customizing other aspects of rendering.

import { useHref, useLinkClickHandler } from "react-router-dom";
import { styled } from "styled-components"; // could be whatever

const StyledLink = styled.a`
  color: fuschia;
`;

const Link = React.forwardRef(
  ({ onClick, replace = false, state, target, to, ...rest }, ref) => {
    let href = useHref(to);
    let handleClick = useLinkClickHandler(to, { replace, state, target });

    return (
      <StyledLink
        {...rest}
        href={href}
        onClick={event => {
          onClick?.(event);
          if (!event.defaultPrevented) {
            handleClick(event);
          }
        }}
        ref={ref}
        target={target}
      />
    );
  }
);

Though the internals of Link in react-router-native are much simpler, I added the hook there for feature parity between the two packages.

@hugmanrique
Copy link

hugmanrique commented Sep 3, 2021

This looks like a great replacement for the as/component prop, effectively moving react-router's state up the tree into user-defined components. This solves all concerns I had on #7598.

@chaance chaance changed the title Features: useLinkClick and useLinkPress Features: useLinkClickHandler and useLinkPressHandler Sep 3, 2021
@chaance chaance merged commit a5583ba into dev Sep 3, 2021
@timdorr timdorr deleted the use-link-click-handler branch September 14, 2021 11:45
brophdawg11 pushed a commit that referenced this pull request Mar 27, 2024
…el plugins (#7998)

Co-authored-by: Mark Dalgleish <mark.john.dalgleish@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants