Home > Enterprise >  OnClick even react typescript is not working
OnClick even react typescript is not working

Time:10-27

I am, new to typescript I am tying to make this onclick work but everything compiles fine but the click Handel function is never getting run ? any idea why ?

import react, { useState } from 'react';
import { render } from 'react-dom';

// Set interface !!
interface Props {
  count?: number;
}

const App: React.FC<Props> = () => {
  const [count, setCount] = useState(0);

  // METHOD
  const handleClick = () => (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    //const type: string = event.currentTarget.title;
    // setCount((prevcount) => (type === 'decrement' ? prevcount - 1 : prevcount   1));
  };

  return (
    <div>
      <button title='decrement' onClick={handleClick}>
        -
      </button>
      {count}
      <button title='increment' onClick={handleClick}>
         
      </button>
    </div>
  );
};

export default App;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You have an extra () => which makes handleClick a function that returns another event handler function instead of just a function that logs to the console.

Change

  const handleClick = () => (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    //const type: string = event.currentTarget.title;
    // setCount((prevcount) => (type === 'decrement' ? prevcount - 1 : prevcount   1));
  };

To

  const handleClick = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    //const type: string = event.currentTarget.title;
    // setCount((prevcount) => (type === 'decrement' ? prevcount - 1 : prevcount   1));
  };
  • Related