Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Button onClick doesn't work with useToggle hook

There is a button that when click it toggles a value. Based on this value, the button has an icon or another icon.

Here is the code:

export const useToggle = (initialState = false) => {
  const [state, setState] = useState(initialState);
  const toggle = useCallback(() => setState((state) => !state), []);
  return [state, toggle];
};


export function Sidebar({ isOpenedInitial }: SidebarProps) {
  const [isOpened, setSidebarState] = useToggle(isOpenedInitial);

  ...
  return (
    <div>
      <button onClick={setSidebarState}>{isOpened ? <OneIcon /> : <AnotherIcon />}</button>
  ...
  )
}

It works but it has a red line under onClick word which says the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type ‘boolean | (() => void)’ is not assignable to type
‘MouseEventHandler | undefined’. Type ‘false’ is
not assignable to type ‘MouseEventHandler |
undefined’

I’ve googled this message, found a question about it here where the accepted answer states to change from onClick={setSidebarState} to onClick={() => setSidebarState}.

The change was made, there is no warning anymore but the button doesn’t work now. I click on it and nothing happens.

Any ideas?

>Solution :

If you mark return value of useToggle as const it will infer correct type of second element of array

export const useToggle = (initialState = false) => {
  const [state, setState] = useState(initialState);
  const toggle = useCallback(() => setState((state) => !state), []);
  return [state, toggle] as const;
};

export function Sidebar() {
  const [isOpened, setSidebarState] = useToggle();

  return (
    <div>
      <button onClick={setSidebarState}>{isOpened ? ... : ...}</button>
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading