Reputation: 3
I am creating a simple button via mui but I want to activate the function when I click it but when I enter the web page, it automatically alerts me. I don't know why it is. The function gets called as soon as the page loads without clicking the button.
const Rece = () =>
{
const userId = localStorage.getItem("currentUser");
function submitLiking(name) {
alert("/"+name+"/" + userId);
/* GetWithAuth("/"+name+"/" + userId)
.then(res => res.json())
.then(
(result) => {
console.log(result);
},
(error) => {
console.log(error)
}
)*/
}
const handleEvent = () => {
alert("I was clicked");
};
return (
<div className='listItem-wrap'>
<Button variant="outlined" onClick={submitLiking("favorite")}>Outlined</Button>
<Button variant="outlined" onClick={submitLiking("remember")}>Outlined</Button>
<Button variant="outlined">Outlined</Button>
</div>
)};
export default Rece;
Upvotes: 0
Views: 65
Reputation: 71
Just try to use event.PreventDefault() or event.stopPropogation() once insde the function https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
Upvotes: -1
Reputation: 31508
The statement submitLiking("…")
is evaluated directly. What you should do is define a proper callback:
onClick={() => submitLiking("favorite")}
Upvotes: 2