Search code examples
typescriptreact-forwardref

Forwarded Ref typescript: forwarding react element


Code:

import React, { useImperativeHandle, useState } from 'react';


const SnackBar = React.forwardRef((_, ref) => {
  const [isSnackbarVisible, setisSnackbarVisible] = useState(false);

  const show = (text: string) => {
    setisSnackbarVisible(true);
  };

  const hide = () => {
    setisSnackbarVisible(false);
  };

  useImperativeHandle(ref, () => ({ show, hide }));

  if (!isSnackbarVisible) return;

  return (
    <div
      style={{ backgroundColor: 'rgba(0, 0, 0, 0.35)' }}
      className="absolute z-50 top-0 bottom-0 left-0 right-0  flex items-center justify-center"
    >
      <button
        onClick={() => {
          hide();
        }}
      >
        dasdas
      </button>
    </div>
  );
});

export default SnackBar;

Error:

 Argument of type '(_: {}, ref: ForwardedRef<unknown>) => Element | undefined' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, {}>'.
  Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>> | null'.
    Type 'undefined' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>> | null'.ts(2345)

How would be the types here?


Solution

  • When your Snackbar is invisible, you are returning an implicit undefined which is not compatible with the method signature. You can find this hint in the last line of your posted error message.

    Try changing this line of your code either to an empty element

    if (!isSnackbarVisible) return <></>;
    

    Or null:

    if (!isSnackbarVisible) return null;