I would like to able to able to trigger a function when I'm using a custom button component, adding onClick directly doesn't work.
Button.tsx
import React from 'react';
export interface ButtonProps {
rounded: 'small' | 'medium' | 'full';
label: string;
icon?: string;
size: 'small' | 'medium' | 'full';
type: 'outline' | 'quiet' | 'fill';
disabled?: boolean;
variant: 'accent' | 'primary' | 'secondary';
}
export const Button = ({
rounded,
label,
icon,
size,
type,
disabled,
variant,
}: ButtonProps) => {
const disabledStyles = 'bg-gray-200 cursor-not-allowed';
const sizeSmall = 'px-4 py-2';
const sizeMedium = 'px-6 py-3';
const sizeLarge = 'px-8 py-4';
return (
<>
<button
type="button"
className={`rounded focus:outline-none focus:ring-[3px] inline-flex justify-center
${disabled === true && disabledStyles}
${size?.toLowerCase() === 'small' && sizeSmall}
${size?.toLowerCase() === 'medium' && sizeMedium}
${size?.toLowerCase() === 'large' && sizeLarge}`}
>
${label}
</button>
</>
);
};
I want to trigger myFunction when button is clicked
import {Button} from myLibraryName;
const myFunction = () => {
console.log('function passed')
}
return <Button [arguments] />
CodePudding user response:
You need to pass down the onClick as a button prop, then in the Button
component you need to add it to the ButtonProps
interface. Then simply pass it down the the button
element inside the render function.
Your Button.tsx will look something like this:
import React from 'react';
export interface ButtonProps {
rounded: 'small' | 'medium' | 'full';
label: string;
icon?: string;
size: 'small' | 'medium' | 'full';
type: 'outline' | 'quiet' | 'fill';
disabled?: boolean;
variant: 'accent' | 'primary' | 'secondary';
onClick: () => void;
}
export const Button = ({
rounded,
label,
icon,
size,
type,
disabled,
variant,
onClick,
}: ButtonProps) => {
const disabledStyles = 'bg-gray-200 cursor-not-allowed';
const sizeSmall = 'px-4 py-2';
const sizeMedium = 'px-6 py-3';
const sizeLarge = 'px-8 py-4';
return (
<>
<button
onClick={onClick}
type="button"
className={`rounded focus:outline-none focus:ring-[3px] inline-flex justify-center
${disabled === true && disabledStyles}
${size?.toLowerCase() === 'small' && sizeSmall}
${size?.toLowerCase() === 'medium' && sizeMedium}
${size?.toLowerCase() === 'large' && sizeLarge}`}
>
${label}
</button>
</>
);
};
and the function will be passed down like:
import {Button} from myLibraryName;
const myFunction = () => {
console.log('function passed')
}
return <Button ...arguments onClick={myFunction} />