Home > Blockchain >  Is there a better way of typing a forwarded ref in MUI?
Is there a better way of typing a forwarded ref in MUI?

Time:07-07

I am using a customized, forwarded checkbox so I can pass that as a component to a DataGrid.

const CustomCheckbox = ({
  checkboxRef,
  ...props
}: {
  checkboxRef: React.ForwardedRef<unknown>;
}) => (
  <Checkbox
    {...props}
    ref={checkboxRef as React.RefObject<HTMLButtonElement>}
    sx={{
      color: "#363636",
      "&.Mui-checked": {
        color: "#363636"
      }
    }}
  />
);

const ForwardCustomCheckbox = forwardRef((props, ref) => {
  return <CustomCheckbox {...props} checkboxRef={ref} />;
});


<DataGrid
  ...
  components={{
    BaseCheckbox: ForwardDarkCheckbox
  }}
/>

I don't like the use of as React.RefObject<HTMLButtonElement> since I understand this as a kind of bypassing TypeScript. I couldn't make it work without that.

Do you have any suggestions or is it considered 'okay' using as in this scenario?

CodePudding user response:

  1. Change checkboxRef type to React.ForwardRef<HTMLButtonElement>, as it seems this is the only element you wish to allow for this property
  2. Use forwardRef<HTMLButtonElement> to explicitly define the type of reference this component accepts
const CustomCheckbox = ({
  checkboxRef,
  ...props
}: {
  checkboxRef: React.ForwardedRef<HTMLButtonElement>;
}) => (
  <Checkbox
    {...props}
    ref={checkboxRef}
    sx={{
      color: '#363636',
      '&.Mui-checked': {
        color: '#363636',
      },
    }}
  />
);

const ForwardCustomCheckbox = forwardRef<HTMLButtonElement>((props, ref) => {
  return <CustomCheckbox {...props} checkboxRef={ref} />;
});
  • Related