Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use more than one property in React Component

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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} />
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading