0

What is the correct type for window.onClick, my linter is not happy with any

import React, { useContext, useState } from 'react';
import { Link } from 'react-router-dom';
import { Global } from '../globalState';
import { Dispatch, LOGGED_IN, SET_MODAL } from '../globalState';

interface PropsInterface {
  avatar: string;
  loggedIn: boolean;
  fullName: string;
}

const TopNav: React.FC<PropsInterface> = (props: PropsInterface) => {
...
window.onclick = (event: any) => {
//                        ^
//                        What is the correct type ??       
    if (
      event.target.id !== 'dropdown'
    ) {
      setState((prev) => ({
        ...prev,
        dropDownStatus: false,
      }));
    }
  };

2 Answers 2

1

For synthetic elements, you can use React.MouseEvent.

Sign up to request clarification or add additional context in comments.

Comments

1

This is defined in the default DOM type definition.

In the most recent version you can find this definition at line 5903 of the lib.dom.d.ts:

...

/**
 * Fires when the user clicks the left mouse button on the object
 * @param ev The mouse event.
 */
onclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;

...

So the correct type would be MouseEvent:

window.onclick = (event: MouseEvent) => { }

If you really want to map the id of the target, you can do something like:

window.onclick = (event: MouseEvent & { target: {id: string}}) => { }

TL;DR

This part doesn't answer the question, but helps to address further trouble.

You want that the dropdown closes, if anything but the dropdown was clicked, right? I think you are better of with adding a reference to the dropdown and compare this instead of the id:

2 Comments

I get a new error Property 'id' does not exist on type 'EventTarget'.ts(2339) on event.target.id
@Bill: Please open another question, if you have troubles implementing off click handling, as this question is about something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.