Reputation: 142
I am trying to build the project and would like to deploy it to vercel but getting some type errors.
The site runs fine in development (using yarn dev).
These are the two functions am using to close a modal without event propagation.
//Closes the modal
const exitModal = (e) => {
closeModal(false)
//this part stops the click from propagating
if (!e) var e = window.event
e.cancelBubble = true
if (e.stopPropagation) e.stopPropagation()
}
const exitAndRefresh = (e) => {
exitModal(e)
window.location.reload()
}
The JSX below with the onClick function:
<button
className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
onClick={exitModal}
>
Cancel
</button>
Build Error: (using yarn build)
Type error: Subsequent variable declarations must have the same type. Variable 'e' must be of type 'any', but here has type 'Event'.
91 |
92 | //this part stops the click from propagating
> 93 | if (!e) var e = window.event
| ^
94 | e.cancelBubble = true
95 | if (e.stopPropagation) e.stopPropagation()
96 | }
I tried doing this -
//Closes the modal
const exitModal = (e: Event) => {
closeModal(false)
//this part stops the click from propagating
if (!e) var e = window.event
e.cancelBubble = true
if (e.stopPropagation) e.stopPropagation()
}
const exitAndRefresh = (e: Event) => {
exitModal(e)
window.location.reload()
}
But got this error instead:
Type error: Type '(e: Event) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
Types of parameters 'e' and 'event' are incompatible.
Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is missing the following properties from type 'Event': cancelBubble, composed, returnValue, srcElement, and 7 more.
158 | <button
159 | className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
> 160 | onClick={exitModal}
| ^
161 | >
162 | Cancel
163 | </button>
error Command failed with exit code 1.
Upvotes: 0
Views: 365
Reputation: 26394
This segment is an outdated snippet that stops propagation (cross browser):
//this part stops the click from propagating
if (!e) var e = window.event
e.cancelBubble = true
if (e.stopPropagation) e.stopPropagation()
Personally I don't think we should be supporting IE indirectly by including extra code for it...
But anyways you don't need a var
there:
// const exitModal = (e: Event) => {
// ^^^^^^^ don't forget to annotate
e ??= window.event!; // if e is not there set it to window.event
e.cancelBubble = true;
e.stopPropagation?.(); // if stopPropagation exists call it
The exclamation mark there is to tell TypeScript that window.event exists.
This code uses the newest features of JavaScript: nullish coalescing assignment and optional chaining with function calls.
Since you're using a build system implicitly with NextJS you can just use these and don't have to worry about older browsers.
Upvotes: 1