Home > Software design >  How to add 2 fuctions to be excuted in onClick method in React
How to add 2 fuctions to be excuted in onClick method in React

Time:11-17

I want to know how to execute 2 functions handleClose and saveData at the same time in the onClick method.

The place I wanted to execute:

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

Full code:

import { useEffect } from "react";
import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import LinearProgress from "@mui/material/LinearProgress";
import Backdrop from "@mui/material/Backdrop";
import Modal from "@mui/material/Modal";
import Fade from "@mui/material/Fade";
import TextField from "@mui/material/TextField";

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 = () => {
    const [data, setData] = React.useState([]);
    const [loader, setLoader] = React.useState(false);
    const [open, setOpen] = React.useState(false);
    const handleOpen = () => setOpen(true);
    const handleClose = () => setOpen(false);

    const [formData, setFormData] = React.useState({
        id: null,
        avatar: "",
        name: "",
    });

    const saveData = () => {
        fetch("https://61924463aeab5c0017105ebe.mockapi.io/test", {
            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://61924463aeab5c0017105ebe.mockapi.io/test")
            .then((res) => res.json())
            .then(
                (result) => {
                    if (result) {
                        setData(result);
                        setLoader(false);
                    }
                },
                (error) => {
                    console.log(error);
                }
            );
    }, []);

    console.log(formData);

    return (
        <div>
            <Button variant="contained" onClick={handleOpen}>
                Add
            </Button>
            <br />
            <br />
            {loader ? (
                <LinearProgress />
            ) : (
                <TableContainer component={Paper}>
                    <Table sx={{ minWidth: 650 }} aria-label="simple table">
                        <TableHead>
                            <TableRow>
                                <TableCell align="center">ID</TableCell>
                                <TableCell align="center">Name</TableCell>
                                <TableCell align="center">Avatar</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {data.map((row) => (
                                <TableRow
                                    key={row.name}
                                    sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                                >
                                    <TableCell align="center">{row.id}</TableCell>
                                    <TableCell align="center">{row.name}</TableCell>
                                    <TableCell align="center">
                                        <img src={row.avatar} width="25" alt={row.name} />
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </TableContainer>
            )}
            <div>
                <Modal
                    aria-labelledby="transition-modal-title"
                    aria-describedby="transition-modal-description"
                    open={open}
                    onClose={handleClose}
                    closeAfterTransition
                    BackdropComponent={Backdrop}
                    BackdropProps={{
                        timeout: 500,
                    }}
                >
                    <Fade in={open}>
                        <Box sx={style}>
                            <Box
                                component="form"
                                sx={{
                                    "& .MuiTextField-root": { m: 1, width: "25ch" },
                                }}
                                noValidate
                                autoComplete="off"
                            >
                                <div>
                                    <TextField
                                        id="outlined-search"
                                        label="ID"
                                        type="search"
                                        onChange={(text) => {
                                            setFormData({
                                                ...formData,
                                                id: text.target.value,
                                            });
                                        }}
                                    />
                                    <TextField
                                        id="outlined-search"
                                        label="Name"
                                        type="search"
                                        onChange={(text) => {
                                            setFormData({
                                                ...formData,
                                                name: text.target.value,
                                            });
                                        }}
                                    />
                                    <TextField
                                        id="outlined-search"
                                        label="Avatar"
                                        type="search"
                                        onChange={(text) => {
                                            setFormData({
                                                ...formData,
                                                avatar: text.target.value,
                                            });
                                        }}
                                    />
                                </div>
                            </Box>
                            <Button variant="contained" onClick={saveData}>
                                Save
                            </Button>
                        </Box>
                    </Fade>
                </Modal>
            </div>
        </div>
    );
};

export default Home;

CodePudding user response:

<Button variant="contained" onClick={() => {
  saveData();
  handleClose();
}}>
  Save
</Button>

CodePudding user response:

The most straight forward method is to wrap them in a jsx prop. If you did not get what I mean see the example below:

Example:

import react from "react";

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

CodePudding user response:

You can be called any handler or function on the onClick method.

Live Example:

const App = () => {

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

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

  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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related