I'm new to React, and I have a question. I'm creating my own button. And I want to do it in an optimized way, including the attributes of the button itself, for example:
disabled, aria-disabled, type, id
I want to have access to all button attributes, without manually inserting them in an interface. And along with these attributes, also include the new ones I created, for example:
loading, buttonSize, variant
My code in summary is this:
export type ButtonProps = {
icon?: React.ReactElement<HTMLOrSVGElement>;
loading?: boolean;
}
class Button extends React.Component<ButtonProps> {
constructor(props: ButtonProps) {
super(props);
}
get classes(): string {
return classnames(
CSS_CLASSES.ROOT,
this.props.theme === 'outline' && CSS_CLASSES.OUTLINE,
this.props.theme === 'filled' && CSS_CLASSES.FILLED,
this.props.theme === 'tonal' && CSS_CLASSES.TONAL,
this.props.size === 'small' && CSS_CLASSES.SMALL,
this.props.size === 'large' && CSS_CLASSES.LARGE,
this.props.className
)
}
render() {
return (
<button></button>
)
}
}
const ForwardedElement = React.forwardRef<ButtonProps, HTMLButtonElement> (
(props: ButtonProps, ref) => <Button {...props}/>
)
export default ForwardedElement;
CodePudding user response:
You can do it by changing ButtonProps
to this:
export type interface extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
icon?: React.ReactElement<HTMLOrSVGElement>;
loading?: boolean;
}
Then in your render
do this:
render() {
return (
<button {...this.props} />
)
}
CodePudding user response:
type MyProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
text: string
}
const MyButton = ({ text, ...props }: MyProps) => {
return <button {...props}>{text}</button>
}
export default MyButton
Now you can access custom props and properties of a button as well.