Home > OS >  How to declare type 'HTMLButtonElement' into my interface in TSX React?
How to declare type 'HTMLButtonElement' into my interface in TSX React?

Time:09-27

I'm new to Ts, I'm making a custom component for the Popover in MUI, I'm passing trough props, the anchorEl and setAnchorElement in order to position my popover properly.

Based on the example of the documentation :

https://stackblitz.com/run?file=demo.tsx

const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(null);

As you can see this elements are type <HTMLButtonElement>

And this is my custom Component interface.

interface DialogProps {
  title?: string
  children: React.ReactNode
  isOpen: boolean
  setIsOpen(value: boolean): void
  anchorEl: any /* Html button element */
  setAnchorEl: any /* Html button element */
}

I want to remove the "any" type from anchorEl and setAnchorEl but I don't know how to declare this HTML type.

CodePudding user response:

The type of anchorEl is the type you pass to useState, and the setter useState returns is Dispatch<SetStateAction<T>>, so your interface should look like this:

interface DialogProps {
  title?: string
  children: React.ReactNode
  isOpen: boolean
  setIsOpen(value: boolean): void
  anchorEl: HTMLButtonElement | null;
  setAnchorEl: React.Dispatch<React.SetStateAction<HTMLButtonElement | null>>;
}
  • Related