prismicio / prismic-react

React components and hooks to fetch and present Prismic content
https://prismic.io/docs/technologies/homepage-reactjs
Apache License 2.0
154 stars 40 forks source link

fix: forward refs to `<PrismicLink>` components #131

Closed angeloashmore closed 2 years ago

angeloashmore commented 2 years ago

Types of changes

Description

This PR adds support for forwarding refs to <PrismicLink> components. Before this PR, refs were ignored, meaning there was no way to target the rendered element.

In the following example, ref will contain a reference to the rendered <a> element.

const Page = ({ document }) => {
  const ref = useRef(null);

  return (
    <PrismicLink ref={ref} field={document.data.link}>
      Click me!
    </PrismicLink>
  );
};

If a custom component is provided, the ref will be passed to the component. The custom component must handle the ref forwarding itself.

const CustomComponent = React.forwardRef(({ href, children }, ref) => {
  return <span ref={ref}>{children}</span>;
});

const Page = ({ document }) => {
  const ref = useRef(null);

  return (
    <PrismicLink
      ref={ref}
      field={document.data.link}
      internalComponent={CustomComponent}
    >
      Click me!
    </PrismicLink>
  );
};

This works for both internal and external components. If you are using TypeScript, note that this means the ref must be typed for both the rendered internal and external components.

Fixes #128

Checklist:

🐡

github-actions[bot] commented 2 years ago

size-limit report 📦

Path Size
dist/index.js 4.42 KB (+0.79% 🔺)
dist/index.cjs 6.3 KB (+0.5% 🔺)