I have like 30 or so buttons in my react app. and i don't want to add event-Listener to each and every button. but every button has a specific job to do. So is there any way i can achieve this.
something like this(its depreciated now):
$("button").click(() => {
fetch("https://reqres.in/api/users/" + this.value)
.then((res) => res.json())
.then((result) => setUser(result));
});
I added the same class names to DOM elements which you want to add the event listeners and those elements by using getElementsByClassNames method. Then, added the event listener to them.
let count = 0;
function onClick() {
document.getElementById("count").innerText = count++;
}
const buttons = document.getElementsByClassName("btn-multiple");
[...buttons].forEach(btn => btn.addEventListener("click", onClick));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple scroll example</title>
<style>
</style>
</head>
<body>
<section id="clear-section" class="clear-section">
<input type="button" value="V1" class="btn-multiple" />
<input type="button" value="V2" class="btn-multiple" />
<input type="button" value="V3" class="btn-multiple" />
<input type="button" value="V4" class="btn-multiple" />
<input type="button" value="V5" class="btn-multiple" />
<input type="button" value="V6" class="btn-multiple" />
<p id="count"></p>
</section>
</body>
</html>