Skip to content

Instantly share code, notes, and snippets.

@the-creature
Created March 6, 2020 04:50
Show Gist options
  • Save the-creature/1e09cb44775e4fa54f6ff3ca06573817 to your computer and use it in GitHub Desktop.
Save the-creature/1e09cb44775e4fa54f6ff3ca06573817 to your computer and use it in GitHub Desktop.
import React, { useCallback } from 'react';
import { ButtonBase, ChildrenWrapper } from './Button.styles';
export interface ButtonProps {
variant?: 'primary' | 'icon';
rounded?: boolean;
outlined?: boolean;
disabled?: boolean;
children: React.ReactNode;
iconLeft?: React.ReactNode;
iconRight?: React.ReactNode;
onBlur?: () => void;
onClick?: () => void;
onFocus?: () => void;
}
export const Button = (props: ButtonProps) => {
const {
variant = 'primary',
iconLeft,
iconRight,
rounded = false,
outlined = false,
disabled = false,
children,
onClick,
onBlur,
onFocus,
...rest
} = props;
const renderClassNames = useCallback(() => {
return [
`button-${variant}`,
rounded && `button--rounded`,
outlined && `button--outlined`,
iconLeft && `button--left-icon`,
iconRight && `button--right-icon`
];
}, [variant, rounded, outlined, iconLeft, iconRight]);
const classes = renderClassNames();
const renderContent = useCallback(() => {
if (iconLeft) {
return (
<React.Fragment>
{iconLeft}
<ChildrenWrapper>{children}</ChildrenWrapper>
</React.Fragment>
);
}
if (iconRight) {
return (
<React.Fragment>
<ChildrenWrapper>{children}</ChildrenWrapper>
{iconRight}
</React.Fragment>
);
}
return <React.Fragment>{children}</React.Fragment>;
}, [iconLeft, children, iconRight]);
return (
<ButtonBase
className={classes.filter(Boolean).join(' ')}
onClick={onClick}
onBlur={onBlur}
onFocus={onFocus}
disabled={disabled}
{...rest}
>
{renderContent()}
</ButtonBase>
);
};
export default Button;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment