️ feat: make the button component to forward ref

This commit is contained in:
Wahyu Kurniawan 2024-02-20 22:59:31 +07:00
parent 2ac657c32e
commit 0f7c6c73c9
No known key found for this signature in database
GPG Key ID: 040A1549143A8E33

View File

@ -1,4 +1,4 @@
import React, { useCallback } from 'react';
import React, { forwardRef, useCallback } from 'react';
import type { ComponentPropsWithoutRef, ReactNode } from 'react';
import { buttonTheme } from './Button.theme';
@ -64,7 +64,12 @@ export type ButtonOrLinkProps = (ButtonLinkProps | ButtonProps) &
/**
* A custom button component that can be used in React applications.
*/
const Button = ({
const Button = forwardRef<
HTMLButtonElement | HTMLAnchorElement,
ButtonOrLinkProps
>(
(
{
children,
className,
leftIcon,
@ -74,7 +79,9 @@ const Button = ({
shape,
variant,
...props
}: ButtonOrLinkProps) => {
},
ref,
) => {
// Conditionally render between <NextLink>, <a> or <button> depending on props
// useCallback to prevent unnecessary re-rendering
const Component = useCallback(
@ -154,6 +161,8 @@ const Button = ({
return (
<Component
{...props}
// @ts-expect-error - ref is not a valid prop for button elements
ref={ref}
className={buttonTheme({ ...styleProps, class: className })}
>
{cloneIcon(leftIcon, { ...iconSize })}
@ -161,7 +170,8 @@ const Button = ({
{cloneIcon(rightIcon, { ...iconSize })}
</Component>
);
};
},
);
Button.displayName = 'Button';