Search code examples
reactjsmodal-dialogantd

antd modal on modal click not opening


I have an antd modal as shown in the below code, Now when I select Create Manual and click Next, I want to close this modal and open another Modal2 but another modal is not getting opened after clicking next.

Here is my code. ( Codesandbox live demo - link )

Please suggest a workaround to get his second modal generated. Thanks

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Modal, Button, Radio } from "antd";

const App = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectRadio, setselectRadio] = useState("preselect");
  const showModal = () => {
    setIsModalVisible(true);
  };
  const select = (e) => {
    // you can save the value in here
    setselectRadio(e.target.value);
    console.log(e.target.value);
  };
  function modalclick() {
    if (selectRadio === "preselect") {
      alert("pre-select");
    } else {
      //---------------> UNABLE TO OPEN ANOTHER MODAL HERE   <-------------------------------------
      <Modal title="Create Test Suite" visible={isModalVisible}>
        MODAL 2 COMES HERE
      </Modal>;
      alert("manual");
    }
  }

  return (
    <>
      <Button type="primary" style={{ float: "right" }} onClick={showModal}>
        Create Test Suite
      </Button>
      <Modal
        title="Create Test Suite"
        visible={isModalVisible}
        footer={[
          <Button key="cancel" onClick={() => setIsModalVisible(false)}>
            Cancel
          </Button>,

          <Button type="primary" key="next" onClick={modalclick}>
            Next
          </Button>
        ]}
      >
        <Radio.Group
          defaultValue="preselect"
          buttonStyle="solid"
          onChange={(e) => {
            select(e);
          }}
        >
          <Radio value="preselect">Create from Preselect</Radio>
          <Radio value="manual">Create Manual</Radio>
        </Radio.Group>
      </Modal>
    </>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));

Solution

  • To show the modal 2 you can use a useState hook or a useRef hook. In both methods, you need first to put this modal 2 in the return of your "App".

    useState way: Just use a state to control the visibility, like how you do in modal 1, simple.

    useRef way: This is a little more complex. You will need to use a useImperativeHandle inside the modal component, and create a function (inside too) to control the visibiliity. So, in your page, you can just call the function that is inside the component, to show the modal. Using this method, the logic about the state control of visibility leaves the page and goes into the component.