Home > other >  creating a popup without onclick
creating a popup without onclick

Time:10-26

I am trying to create a popup inside an async function. The popup would right before creating the election but I am not sure how to handle/call it. The message is always the same

import Popup from '../Popup.js'


async function GenerateElection() {
                    

        const election = await Axios.post("/addElection", {electionInfo}, { headers: { "token" : localStorage.getItem("token") }});

here where election is called

<Button variant = "contained" style = {{width: 150}} onClick={() => {GenerateElection()}}>Generate Election</Button>

I have a very basic popup.js page

import React from "react";
const Popup = props => {
return (
<div className="popup-box">
  <div className="box">
    <span className="close-icon" onClick={props.handleClose}>x</span>
    Election is being generated, please wait.
  </div>
</div>
);
};
export default Popup;

CodePudding user response:

You can use hook useRef to create a reference for Popup and after calling function, add the class .show to make it visible.

import React, { useRef } from "react";

const Popup = props => {
  const popupRef = useRef(null); // Here is a reference
  return (
    <div className="popup-box" ref={popupRef}>
      <div className="box">
        <span className="close-icon" onClick={props.handleClose}>x</span>
        Election is being generated, please wait.
      </div>
    </div>
  );
};
export default Popup;

and then call synchronous function with Promise instead of async/await

function GenerateElection() {
  popupRef.current.classList.add('show');

  Axios.post(*skipped part*).then(res => {
    const election = res.data
  });

<Button onClick={GenerateElection}>Generate Election</Button>

CodePudding user response:

add a variable in the component where there is a button, for example popup, and fill it in as needed. Also, you don't have to use the arrow function in onClick if you don't pass parameters. onClick={GenerateElection}

  const [popup, setPopup] = useState(null);

  async function GenerateElection() {
    setPopup(<Popup />)
    const election = await Axios
    .post("/addElection", {electionInfo}, {
       headers: { "token" : localStorage.getItem("token")}
      }
    );
    setPopup(null) // for hide
  }

  return (
    <div>
      {popup && popup}
      <Button variant="contained" style={{width: 150}} onClick={GenerateElection} >Generate Election</Button>
    </div>
  );
  • Related