Home > Blockchain >  How to pass a function as a parameter in typescript functional component
How to pass a function as a parameter in typescript functional component

Time:01-05

I want to pass a function and a number as parameters to a typescript functional component, I used the any keyword and there wasn't any error from the ide but when i ran the code, the error from the browser's console was the following. using javascript the code works as expected, please any idea how i can fix this error

react-dom.development.js:4054 Uncaught Error: Expected `onClick` listener to be a function, instead got a value of `object` type.
    at getListener (react-dom.development.js:4054:1)
    at accumulateSinglePhaseListeners (react-dom.development.js:9317:1)
    at extractEvents$4 (react-dom.development.js:8976:1)
    at extractEvents$5 (react-dom.development.js:9004:1)
    at dispatchEventsForPlugins (react-dom.development.js:9096:1)
    at react-dom.development.js:9288:1
    at batchedUpdates$1 (react-dom.development.js:26140:1)
    at batchedUpdates (react-dom.development.js:3991:1)
    at dispatchEventForPluginEventSystem (react-dom.development.js:9287:1)

Uncaught TypeError: handleDrawerToggle is not a function

// Typescript
const App = () => {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const drawerWidth = 240;
  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };
  return (
    <div>
      <Sample
        handleDrawerToggle={handleDrawerToggle}
        drawerWidth={drawerWidth}
      />
      {mobileOpen && <h1>hello</h1>}
    </div>
  );
};

const Sample = ( handleDrawerToggle:any, drawerWidth:any ) => {
  return (
    <div>
      <button onClick={handleDrawerToggle} style={{ width: `${drawerWidth}` }}>
        Testv
      </button>
    </div>
  );
};

CodePudding user response:

Rather than passing as any, you can be more specific and pass it as () => void. I would also advice to add a prop type.

For example, type SampleProps = { handleDrawerToggle: () => void; drawerWidth: number }

So something like

const Sample = ({ handleDrawerToggle, drawerWidth }: SampleProps) => {
  return (
    <div>
      <button onClick={handleDrawerToggle} style={{ width: `${drawerWidth}px` }}>
        Testv
      </button>
    </div>
  );
};

CodePudding user response:

You forgot the {} for the props of you component :

const Sample = ({ handleDrawerToggle, drawerWidth }) => {
  return (
    <div>
      <button onClick={handleDrawerToggle} style={{ width: `${drawerWidth}` }}>
        Testv
      </button>
    </div>
  );
};

With your code handleDrawerToggle is like props if don't write the {} and props is an object.

  • Related