Skip to content Skip to sidebar Skip to footer

Rendering Modal Popup

My goal is to launch a modal pop-up during the event a button is clicked. I've been having issues making the Axios API call to the function that contains the modal. The process of

Solution 1:

Instead of having a show state in your Example component, receive this data in a prop. In addition, you'll also want to pass some callbacks to the component to be able to react to certain events (e.g. clicking "Close" or "Save Changes").

I'd do the following:

constExample = ({ show, onClose, onSave }) => (
  <Modalshow={show}onHide={onClose}><Modal.HeadercloseButton><Modal.Title>Modal heading</Modal.Title></Modal.Header><Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body><Modal.Footer><Buttonvariant="secondary"onClick={onClose}>
        Close
      </Button><Buttonvariant="primary"onClick={onSave}>
        Save Changes
      </Button></Modal.Footer></Modal>
)

This way you could always render the Example component in some parent component and show it conditionally, like so:

constSomeParentComponent = () => {
  const [showExample, setShowExample] = useState(false)

  constaddToCart = () => {
    Axios.post("http://example.com/api/add-to-cart")
      .then((res) => {
        console.log("post called")
        setShowExample(true)
      })
      .catch((err) => {
        if (err.response && err.response.status === 401) {
          setIsLoggedIn(false);
        }
      })
  }

  return (
    <><buttonclassName="button is-primary"onClick={addToCart}>
        ADD TO CART
      </button><Exampleshow={showExample}onClose={() => setShowExample(false)}
        onSave={() => setShowExample(false)}
      />
    </>
  )
}

Post a Comment for "Rendering Modal Popup"