Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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:

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Now, you need to explicit say that setSideBarState is a function, so you need to put setSideBarState()

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda