Skip to content

Commit

Permalink
fix: forwardRef from SideNavigationLink component
Browse files Browse the repository at this point in the history
  • Loading branch information
aaryanporwal committed Sep 5, 2024
1 parent 63c11c9 commit 9d67f7e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import type { ButtonHTMLAttributes } from "react";

import SideNavigationLink from "./SideNavigationLink";

Expand Down Expand Up @@ -32,11 +31,11 @@ it("displays a dark icon", () => {
});

it("can use a custom link component", () => {
const Link = ({ ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props} />
const Link = ({ to }: { to: () => void }) => (
<button onClick={to}>link</button>
);
const label = "Test content";
render(<SideNavigationLink label={label} component={Link} />);
render(<SideNavigationLink label={label} component={Link} to={jest.fn()} />);
expect(screen.getByRole("button", { name: label })).toHaveClass(
"p-side-navigation__link",
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { forwardRef } from "react";
import React from "react";
import classNames from "classnames";
import type { HTMLProps } from "react";

Expand All @@ -16,22 +16,30 @@ export type Props<L = LinkDefaultElement> = Omit<
* @default a
*/
component?: SideNavigationBaseProps<L>["component"];
/**
* A ref to pass to the link element.
*/
forwardRef?: React.Ref<HTMLAnchorElement> | null;
};

const SideNavigationLink = <L = LinkDefaultElement,>({
component,
forwardRef,
...props
}: Props<L>) => {
let className: string | null = null;
if ("className" in props && typeof props.className === "string") {
className = props.className;
delete props.className;
}
return (
<SideNavigationBase
className={classNames("p-side-navigation__link", className)}
component={component ?? "a"}
{...props}
ref={forwardRef}
/>
);
};
const SideNavigationLink = forwardRef<HTMLAnchorElement, Props>(
({ component, ...props }: Props) => {
let className: string | null = null;
if ("className" in props && typeof props.className === "string") {
className = props.className;
delete props.className;
}
return (
<SideNavigationBase
className={classNames("p-side-navigation__link", className)}
component={component ?? "a"}
{...props}
/>
);
},
);

export default SideNavigationLink;

0 comments on commit 9d67f7e

Please sign in to comment.