Skip to content

Instantly share code, notes, and snippets.

@yotam707
Created June 3, 2022 12:10
Show Gist options
  • Save yotam707/b79e40b66e717179c5404c1e3e7259ad to your computer and use it in GitHub Desktop.
Save yotam707/b79e40b66e717179c5404c1e3e7259ad to your computer and use it in GitHub Desktop.
import {
Button as ChakraButton,
ButtonProps,
forwardRef,
useStyleConfig,
} from '@chakra-ui/react';
import { useCallback, MouseEvent } from 'react';
import { Loader } from 'src/components/common/Loader';
import { FormattedMessage } from 'react-intl';
import analytics, { AnalyticsPropsType } from 'src/services/analytics';
import { ButtonSizes, ButtonVariants } from './consts';
type Props = ButtonProps &
AnalyticsPropsType & {
variant?: ButtonVariants;
size?: ButtonSizes;
label?: string;
values?: Record<string, any>;
testId?: string | null;
};
export const Button = forwardRef<Props, 'button'>(
(
{
size,
variant,
label,
values,
onClick,
testId,
analyticsProperties,
...rest
},
ref,
) => {
const styles = useStyleConfig('Button', { size, variant });
const dataTestId = testId || `button-${label}`;
const onClickWithEvent = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
if (label) {
analytics.trackAction(label, analyticsProperties);
}
return onClick && onClick(event);
},
[onClick, label, analyticsProperties],
);
return (
<ChakraButton
sx={styles}
ref={ref}
iconSpacing={2}
spinner={<Loader />}
onClick={onClickWithEvent}
data-testid={dataTestId}
{...rest}
>
<FormattedMessage defaultMessage={label} values={values} />
</ChakraButton>
);
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment