Siddhut
Siddhut

Reputation: 377

How to invoke a modal on function response in React?

I want to invoke something like a function call inside of a response so that I can open up a modal. I'm using material ui for the modal.

Modal

The flow goes with something like

  1. Click on a button
  2. Send request
  3. Get response and display message in Modal.

The modal exists as a separate component so i cannot do


.then( e => {
        <Modal />
       })

Tried including the modal hook in the same file but doesn't work like that.

axios
      .post(`${url}`, {
        email: email
      })
      .then(res => {
        if (res.data.type === "account not found") {
          <WarningModal />
        } else if (res.data.type === "email sent") {
          <SuccessModal />
        }
      });

Just want to invoke modal components on receiving response.

Upvotes: 3

Views: 12190

Answers (3)

akano1
akano1

Reputation: 41634

Add 2 state variable for both modals and set them true in the axios call, also add the modal to the return.

const test = () => {
    const [showSuccessModal, setShowSuccessModal] = useState(false)
    const [showWarningModal, setShowWarningModal] = useState(false)


    axios
      .post(`${url}`, {
        email: email
      })
      .then(res => {
        if (res.data.type === "account not found") {
          setShowWarningModal(true)
        } else if (res.data.type === "email sent") {
            setShowSuccessModal(true)
        }
      });

    return (
        <div>
            <WarningModal open={showWarningModal}/>
            <SuccessModal open={showSuccessModal} />
        </div>
    )

}

Upvotes: 2

Edrian
Edrian

Reputation: 608

What you want to do is this:

  1. Add your Modal component to your component's render function. Like so:
  2. Hook the open prop of the Modal component to a state, call it openModal. Now you have this.state.openModal.
  3. On request response, do a this.setState({openModal: true})
  4. The modal should now be opening.

You should have something like this:

render() => {
       return (
          ...
          <Modal open={this.state.openModal}/>
       )
    }

Upvotes: 1

Arnaud Christ
Arnaud Christ

Reputation: 3551

As you may have noticed, the Modal component from material-ui takes an open prop indicating whether the modal is open or not.

So what you have to do is to put the modal somewhere in your JSX with the open prop set to a boolean value coming from your component's state. And when you receive the response from your HTTP call, you toggle this boolean to true, and the modal will appear.

Upvotes: 2

Related Questions