In Typescript, which kind of event is suitable for MouseEvent<HTMLDivElement>?

My goal is to close the modal when clicking outside the div element. Take a look at my code below.


// The onClose function is a setState(false) function.

import { useRef, useEffect } from 'hooks'
import { MouseEvent } from 'react'
import { MovieInfo } from 'types/movie'

interface Props {
  info: MovieInfo
  onClose: () => void
}

const Modal = ({ info, onClose }: Props) => {
  const modalRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  })

  const handleClickOutside = (e: MouseEvent<HTMLDivElement>) => {
    if (e.target.id === 'modal-container') onClose()
  }

  return (
    <div id='modal-container' ref={modalRef}>
      <div>
        <button type='button' onClick={onClose}>
          close
        </button>
      </div>
    </div>
  )
}

export default Modal

This is my Component where I have been working on my code

  const handleClickOutside = (e: any) => {
    if (e.target.id === 'modal-container') onClose()
  }

In the above code snippet, I used e:any, and everything seemed fine.

However, after removing e:any and adding

e:MouseEvent<HTMLDivElement>
,

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  })

  const handleClickOutside = (e: MouseEvent<HTMLDivElement>) => {
    if (e.target.id === 'modal-container') onClose()
  }

The implementation of this useEffect hook and function resulted in errors being thrown.

Specifically, two occurrences of handleClickOutside are marked as errors, as well as the usage of id.

Furthermore, VScode gives an tooltip stating No overload matches this call. for both instances.

If you notice any mistakes or have suggestions, please let me know. Thank you.

Answer №1

import { MouseEvent } from 'react'

This particular type is designed for the events that are emitted by react, such as when utilizing the onClick prop. When subscribing directly to the document, you will receive a native dom event instead of a react event, meaning you should use the type of the dom event. Despite having the same name as the one in react, it does not need to be imported.

To resolve this issue, simply remove the import statement and omit the <HTMLDivElement> part (since the dom event is not generic). Additionally, the type information indicates that e.target may potentially be null, so make sure to validate for null or assert that it is not null.

const handleClickOutside = (e: MouseEvent) => {
    if (e.target?.id === 'modal-container') onClose()
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular unable to send object to HTML page

Struggling with learning angular, encountering new challenges when working with objects in different components. In two separate instances, try to implement two different mechanisms (microservice or service component serving an object directly). This speci ...

Is there a problem with Angular2 using TypeScript?

Currently, I am in the process of setting up my machine for Angular development by following the guidelines provided on https://angular.io/docs/ts/latest/quickstart.html As I proceeded to run "npm start" to launch my site, I encountered an issue with the ...

Issue with VS2017RC: TypeScript fails to produce JavaScript files

After updating to VS 2017, I noticed that modifications made to a typescript file no longer result in the generation of any javascript code, despite receiving a message indicating "outputs generated successfully" on the lower bar. I tested this issue on t ...

What is the process for converting variadic parameters into a different format for the return value?

I am currently developing a combinations function that generates a cartesian product of input lists. A unique feature I want to include is the ability to support enums as potential lists, with the possibility of expanding to support actual Sets in the futu ...

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

Encountering issues with upgrading Vue.js 2.5.2 with TypeScript

I am currently in the process of updating vue js to version 2.5.2 along with typescript 2.5.3. Below is my index.ts file: import Vue from 'vue' var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' ...

Troubleshooting Typescript compilation issues following an upgrade to a React Native project

I am facing a challenge while updating a react native project from version 0.63.3 to 0.67.0. When attempting to run npm run tsc, I encounter numerous errors indicating that the typescript packages are not compatible with their original packages. Here is a ...

Encountering issues with `Partial<this['someProperty']>` usage in TypeScript

Provided class A { props: { bool?: boolean, test: string } = { test: 'a' }; setProps(newPropertiesr: Partial<this['props']>) { } a() { this.setProps({ bool: fals ...

Loading an index.html file using Webpack 3, Typescript, and the file-loader: A step-by-step guide

Attempting to utilize the file-loader and Webpack 3 to load my index.html file is proving to be a challenge. The configuration in my webpack.config.ts file appears as follows: import * as webpack from 'webpack'; const config: webpack.Configura ...

Obtain JSON information in a structured model layout using Angular 4

I have different categories in the backend and I would like to retrieve them in a model format. Here is how my model is structured: export class Category { name: string; id : string; } And this is how the data appears in the backend: { "name": "cars", ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Issue with TypeScript: Rxjs uses different syntax for setTimeout compared to what is defined in @types/node

System Information: Node version: v11.7.0 RxJS version: 6.3.3 @types/node version: 8.10.45 tsc version: 3.2.4 During the execution of tsc, it appears that there is an issue within Rxjs where the setTimeout function is being called without specifying th ...

"Exploring the process of retrieving URL parameters within an activated link using Angular 7 and executing a REST API call from a service

My aim is to retrieve data by utilizing the id field through Get parameters. Below is the URL code in my HTML that redirects to a specific page without triggering the service to fetch the REST API. <a [routerLink]="['/usedCars/detail', list ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

Loading and unloading an Angular 6 component

One challenge I'm facing involves creating an image modal that appears when an image is clicked. Currently, I have it set up so that the child component loads upon clicking the image. However, the issue is that it can only be clicked once and then dis ...

Unveiling the magic behind using jasmine to spy on a generic

I am trying to spy on a generic method in TypeScript, but Jasmine is not recognizing it. Here is the code snippet: http: HttpClient <- Not actual code, just showing type. ... this.http.get<Customer[]>(url); In this code, I am trying to mock the ...

Issue regarding custom CSS implementation in Angular project

Being a French speaker, I apologize in advance for any mistakes I might make. I am also fairly new to Angular, so if you could provide detailed explanations in your responses, it would be greatly appreciated. Thank you. I am trying to import a custom CSS ...

Explaining how to use the describe function in TypeScript for mapping class constructors

I am working on a function that will return a JavaScript Object with the class instances as values and the class names as keys. For example: const init = (constructorMap) => { return Object.keys(constructorMap).reduce((ret, constructorName) => ...