I want to create a button in typescript that when clicked it runs a function, I did it but it fails in build(project in next js)
button.tsx
import { tw } from 'twind';
interface IButton {
primary?: boolean;
children: React.ReactNode | string;
modifier?: string;
}
const Button = ({ primary, modifier, children, ...rest }: IButton) => {
const baseStyle = `font-sans font-medium py-2 px-4 border rounded`;
const styles = primary
? `bg-indigo-600 text-white border-indigo-500 hover:bg-indigo-700`
: `bg-white text-gray-600 border-gray-300 hover:bg-gray-100`;
return (
<button type="button" className={tw(`${baseStyle} ${styles} ${modifier ?? ``}`)} {...rest}>
{children}
</button>
);
};
export default Button;
and here is where I try to run the onclick function:
const hey = (onClick?: React.MouseEventHandler<HTMLElement>) => {
sendEmail()
setText("Thank you!")
}
<Button onClick={hey}>{text}</Button>
CodePudding user response:
Probably, the TypeChecker will fail as onClick is not part of the Button interface.
Either add only onClick
to the IButton
interface or use the following:
const Button = ({ ... }: IButton & React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>) => { ... }
This way you can add any props valid for button
to your Button
.