Reputation: 31
my function is like this:
async function handleFavorites(event: MouseEvent) {
event.preventDefault();
}
on my button, I'm using onclick to call this function but it's not working
<button
type="submit"
value={favorites}
onChange={e => setFavorites(e.currentTarget.value)}
onClick={() => {
handleFavorites();
}}
>
Error: Expected 1 arguments, but got 0. An argument for 'event' was not provided.
does anyone know how to solve? or have any tips?
Upvotes: 2
Views: 4458
Reputation: 42228
React has its own "synthetic events" which wrap the underlying native DOM events. The core of your problem is the confusion between the synthetic event and the native event. Your handleFavorites
method is currently expecting a native event, while the button
onClick
provides a synthetic event. With your current types, you could actually do this onClick={e => handleFavorites(e.nativeEvent)}
, though I don't recommend it.
Everyone else is correct that you want to pass your callback as onClick={handleFavorites}
. But in order to do that, your handleFavorites
needs to accept a synthetic event. React and the DOM both have their own interfaces for a MouseEvent
with the same name, so you need to make sure that you are using the right one.
(event: React.MouseEvent)
which makes it clear that this is react synthetic event.(event: MouseEvent)
and import the react version into your file import React, {MouseEvent} from "react";
Note that the native event and the synthetic event both have a preventDefault()
method, so switching the type won't necessitate changes in the function.
Upvotes: 4
Reputation: 107
You don't need to write functions to onclick again. Try it this way.
function handleFavorites(e) {
e.preventDefault();
}
onClick={handleFavorites}
Upvotes: 2
Reputation: 2484
The problem is that you are not passing the event argument to your handler. This should work:
<button
type="submit"
value={favorites}
onChange={e => setFavorites(e.currentTarget.value)}
onClick={handleFavorites}
>
Upvotes: 4