Home > Enterprise >  TypeError: X is not a function
TypeError: X is not a function

Time:02-01

I have a function in the parent component:

const App = () => {
  const ref = useRef<HTMLDivElement>(null);
  const handleRef = () => {
    console.log('ref clicked');
    if (ref.current !== null) {
      ref.current.scrollIntoView({ behavior: 'smooth' });
    }
  };
  return(
    <Header handleRef={handleRef} />
  )

which is passing down handleRef to Header:

const Header = ({ handleRef }: any) => {
  return (
    <Navigation items={data} handleRef={handleRef} />
  )
}

which is passing down handleRef to Navigation:

const Navigation = ({ items }: any, { handleRef }: any) => (
  <div
    className="navigationItem"
    onClick={() => {
      handleRef();
    }}
    onKeyDown={handleRef}
    role="button"
    tabIndex={0}
  >menu item</div>
)

But onClick raises Uncaught TypeError: handleRef is not a function. What am I missing?

CodePudding user response:

Props are passed down to components as a single object, not multiple objects.

const Navigation = ({ items }: any, { handleRef }: any) => (

should be

const Navigation = ({ items, handleRef }: any) => (

You should also not use any, since that defeats the whole purpose of TypeScript. The items looks to be some sort of an array, and the handleRef is a function that takes no arguments and returns nothing, so you should have something like

const Navigation = ({
  items,
  handleRef
}: {
  items: Array<Item>; // insert the type of an array item here
  handleRef: () => void;
}) => (

CodePudding user response:

You are passing props incorrectly. From the definition of your Navigation component, it's expecting two objects instead of one with two keys. Try this:

type Props = { 
  handleRef: () => void;
  items: unknown[]; // replace "unknown" with the correct type
};

const Navigation = ({ handleRef, items }: Props) => (
  ...
);

Note that you shouldn't be using any because that bypasses the type checks and takes away the benefits of using typescript in the first place.

  •  Tags:  
  • Related