Tips for implementing two functions to run within the onClick event handler in React

I am looking to simultaneously execute two functions handleClose and saveData within the onClick method.

The specific location where I want this execution to happen:

                            <Button variant="contained" onClick={saveData}>
                                Save
                            </Button>

Complete code snippet:

import { useEffect } from "react";
import * as React from "react";
import Table from "@mui/material/Table";
// more imports ...

const style = {
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    width: 400,
    bgcolor: "background.paper",
    border: "2px solid #000",
    boxShadow: 24,
    p: 4,
};

const Home = () => {
    // component state variables declaration ...
  
    const saveData = () => {
        fetch("https://apiendpoint.com/data", {
            method: "POST",
            body: JSON.stringify(formData),
            headers: {
                "Content-type": "application/json; charset=UTF-8",
            },
        })
            .then((response) => response.json())
            .then((json) => {
                console.log(json, "Save Data");
                handleClose();
            });
    };

    useEffect(() => {
        setLoader(true);
        fetch("https://apiendpoint.com/data")
            .then((res) => res.json())
            .then(
                (result) => {
                    if (result) {
                        setData(result);
                        setLoader(false);
                    }
                },
                (error) => {
                    console.log(error);
                }
            );
    }, []);

    return (
        <div>
            <Button variant="contained" onClick={handleOpen}>
                Add
            </Button>
            <br />
            <br />
            {loader ? (
                <LinearProgress />
            ) : (
                <TableContainer component={Paper}>
                    // table structure markup ...
                </TableContainer>
            )}
            <div>
                <Modal>
                    // modal content markup ...
                </Modal>
            </div>
        </div>
    );
};

export default Home;

Answer №1

<Button style="background-color: #3498db;" onClick={() => {
  saveChanges();
  closeDialogBox();
}}>
  Update Changes
</Button>

Answer №2

A simple and effective approach is to enclose them in a jsx prop. If this explanation isn't clear, take a look at the following example:

Example:

import React from "react";

const App = () =>{
return(
    <div id="foo-bar">
        <button onClick={()=>{
            foo()
            foo2();
        }}></button>
    </div>
);
}

Answer №3

You have the ability to invoke any handler or function using the onClick method.

Demo:

const App = () => {

  const saveData = () => {
    console.log("save data function called");
  };

  const handleClose = () => {
    console.log("handleClose function called");
  };

  const handleOnClick = () => {
    handleClose();
    saveData();
  };

  return (
    <div>
      <button onClick={handleOnClick}>Save</button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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

React: Implementing dynamic button enablement based on TextField input

Can someone help me figure out how to enable a button immediately after entering a value in a TextField? Currently, the button only becomes enabled when I click outside the TextField after inputting a value. I feel like I am overlooking something simple bu ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

Guide on how to point to a React JS application via Node JS server on the same server

I am working with two separate React JS applications and need to direct users to the appropriate application based on the URL. For example: app.get('/' , (req,res,next) => { // Redirect to the first SPA }); app.get('/admin' , (r ...

Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code: (function(window) { window.smp=function smpSelector(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; if (!s ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Encountering a 404 error when trying to click on 'allow' after using Firebase Cloud Messaging, and attempting to add a service worker manually proves unsuccessful in resolving the issue

Currently, I am working on integrating FCM (Firebase Cloud Messaging) into a React app. Initially, I tested it on a simple project without React and everything worked smoothly. However, implementing it in the React app has presented some challenges for me. ...

Explore the possibilities with Intel XDK's customizable keyboard feature

I recently started using Intel XDK for development and I encountered the following issue: I have an input text field (HTML) and I need to restrict user input to only numbers, decimals, and negative sign when they click on the field. How can I achieve this ...

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

Windowing box inside a container box

I am looking to implement scrolling for just the "chat-messages" div within the "chat-bar" div on my site. I want only this specific section to be scrollable, while the rest of the site remains stationary. Currently, I have to scroll through the entire pag ...

Setting nodeIntegration to false led to an Uncaught ReferenceError: require is not defined when trying to access Object.url (external "url":1) in the electron-react-typescript environment

After setting nodeIntegration to false, I encountered the following error message: "Uncaught ReferenceError: require is not defined at Object.url (external 'url': 1)". Upon clicking on the link referring to "external 'url': 1", it led ...

Begin a SeleniumWebDriver session after Google Chrome has been launched beforehand

I am looking to create an automation using SeleniumWebDriver and Node.js, but I am facing an issue where I cannot start the automation if Google Chrome is already open and in use by the user. Currently, my workaround is to close all instances of Chrome be ...

Click on an image to dismiss a material-ui dialog

Trying to include a clickable image to close a material-ui dialog, but encountering an issue where the onClick event is not responding. The props.onRequestClose function works fine when clicking outside of the dialog. What could be causing this problem? ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

Error with Google Maps Display

My goal is to achieve two things with the code snippet below: If the geocode process is unsuccessful, I want to prevent the map from being displayed (currently, I've only hidden the error message). If the geocode process is successful, I only want t ...

Saving JSON data into an HTML element using Handlebars templating

Is there a way to save the entire JSON object within an HTML element as a data attribute? let a = {name : "sample", age : "34"} $.find('#someDiv').data('adata', a); Is it possible to achieve the same result using Handlebars when creat ...

The DOMException occurred when attempting to run the 'querySelector' function on the 'Document' object

Currently, I am engaged in a project that was initiated with bootstrap version 4.3.1. I have a keen interest in both JavaScript and HTML coding. <a class="dropdown-item" href="{{ route('user.panel') }}"> User panel </a& ...

Dynamic css property implementation in Vue list rendering

I am currently working on creating a carousel-style list of items similar to the iOS native date/time pickers, where the list can be shifted both upwards and downwards. The positioning of each item is determined by the `top` property from a model, which i ...

Upon installing a global npm package, the system encountered an error stating: 'File or directory not found: ENOENT'

After successfully publishing my first Node.js CLI tool package on npm, I encountered an issue when trying to test it by installing it locally. The warning message "Error: ENOENT: no such file or directory" kept showing up. Steps for Reproduction To start ...

JavaScript makes Chrome Hard Reload a breeze

We've created a browser-based app using AngularJS and are currently testing it with a group of clients. One major challenge we're facing is explaining how to "Empty Cache and Hard Reload" using the Chrome browser (by pressing F12, then clicking o ...