What is the reason behind the function being returned in this situation? (JavaScript)

I'm struggling to understand a piece of code related to handling an onClick event in JavaScript/React. Here is the function:

handleButtonClick(key, song) {
    return () => {
        document.getElementById(key).play();
        this.setState({
            currentSongText: song,
        });
    };
}

I'm confused about why it uses return () =>{} inside the body of handleButtonClick. If I remove it, the code stops working. I couldn't find any information on this while searching online, so any advice would be appreciated.

Here's the link to the project: https://codepen.io/koffiekan/pen/eYJqdWW

Answer №1

A callback function is a crucial concept in programming. If you're curious about how they work, check out this informative post on Stack Overflow: What is a callback function

When dealing with onclick events, it's important to provide a function for the event to reference. This way, the event handler can easily point to the function without having to duplicate it each time - promoting code reusability.

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

Are you looking for outcomes related to Bootstrap typeahead feature?

I am facing an issue with returning results for the bootstrap typeahead after making an ajax request. Strangely, it works fine without initiating the ajax request. The code that doesn't work: $(".typeahead").typeahead({ source: function(query, pr ...

Timeout of 30 seconds added to Axios network requests in Javascript

self.$axios .$get( `https://verifiedpro.herokuapp.com/getvmsstate?kiosk=${self.kiosk}` ) .catch(error => { console.log(error); location.reload(); }) .then(response => { console.log(respons ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

What is the best way to retrieve data from Elastic Search using Node.js?

I currently work with NODE JS in conjunction with an elastic search DB. Within this setup, I am utilizing the following package: https://www.npmjs.com/package/@elastic/elasticsearch In my elastic search DB, I have a collection that looks like this: [ { ...

Add a CSS class to the main document via an iframe

Is there a simple method to apply a CSS class that is specifically defined in the head of an iframe to an element located in the main document? Can this be done without having to resort to using JavaScript to copy the class from the iframe's head to ...

Having trouble with Reactjs rendering markup correctly from the `render()` function

Currently, I am still in the process of learning Reactjs. My challenge lies in populating table headers within a table row. The issue I encountered is that the code provided below is treating the generated table headers via the renderTableHeaders() funct ...

Node.js does not support MongoDB projection

Here is the code I am working with: result = await mongoDBO.collection(collectionName).find({id: data.id},{projection : {'_id' : 0}}).toArray(); Unfortunately, I encountered the error below: Unsupported projection option: projection: { _id: 0 } ...

Changing the hidden input value to the data-id of a selected <a> element

I've set up a form with a dropdown menu and subdropdowns, generated using a foreach loop through a @Model. When I click on one of the options, I want the value of my hidden input field to match the data-id of the clicked item. This is what I have in ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

Securing Javascript variables from tampering during server submissions - a comprehensive guide

Currently, I am working on developing a basic MVC application in ASP .NET where I want to store all session user data on the client side. This means that every time the page is loaded, the variables reset to zero (e.g., points in a game). The intention is ...

Using JavaScript to link buttons and dynamically change their colors

Just starting to dabble in JavaScript and attempting to change the colors of my website's header, footer, and background. I've created two buttons: <div class="styleBut"> <a href="#" class="btn btn-warning">ReStyle</a> ...

IntelliJ has removed the connect-flash plugin, preventing me from reinstalling it

Learning node.js is new to me and I encountered a strange issue. While working on implementing login functionality with passportjs, I faced an error where req.flash() was not functioning properly. Oddly enough, it was working fine yesterday when I used it ...

The ChartistJs is unable to find the property '_index' of an undefined value, either being 0 or null

I recently incorporated chartistJS to display charts on my website. I have successfully implemented the 'onClick' function provided by chartist. Here is a snippet of the code I used: public horizontalBarchartoptions = { 'onClick&apo ...

Implement multiple selection of parameters in React Material UI version 1.0 and handle the onChange

Currently, I am working on implementing React Material UI 1.0.0-beta.34 and encountering an issue with the Select component. My challenge lies in trying to include an extra parameter in the onChange event handler, yet it seems that only the event parameter ...

Combining arrays and encoding in Json格式

I have a process that generates multiple arrays in PHP: for ($t=0;$t<2;$t++) { for ($xx=0;$xx<$totf[$t];$xx++) { $otdata[$t][$xx] = array("".$otname[$t][$xx]."" => ['games'=> $otg[$t][$xx], 'mint'=> ...

The Find() method in Mongoose and Node.js might return undefined

I recently encountered an issue while working on a simple function in Node.js and Mongoose that should return true if the model is empty. Even though my mongoose configuration seemed perfectly fine: var mongoose = require('mongoose'); var db = ...

Issue with the statement not being recognized for counting the space bar

I created a counter but I'm having trouble incorporating if statements For example: if (hits == 1) {alert("hello world1")} if (hits == 2) {alert("hello world2")} if (hits == 3) {alert("hello world3")} if (hits == 4) {alert("hello world4")} This is t ...

JQuery functionality not functioning properly following an AJAX page reload

Currently, I am utilizing a jQuery code to select all checkboxes in the following manner: var JQ7=jQuery.noConflict(); JQ7(document).ready(function(){ JQ7("#chkAll").click(function(){ JQ7(".chk").prop("checked",JQ7("#chkAll").prop("checked")) }) }); ...

Will the .replaceWith() method alter the code visible to search engines?

After successfully modifying the content of specific H1 elements to not return the value from a global variable using the following code; <script type="text/javascript"> $(document).ready(function() { $("H1").filter(function() { return $(this).text ...

How to insert into an array in MongoDB using Mongoose?

I have an issue with my model where I am attempting to push an array to an empty array, but for some reason the changes are not reflected in Compass. Various approaches were tried to remedy this situation such as setting the type of user_list property to ...