Search code examples
reactjsantdsimplemodal

How do I see modal by clicking image in react??(instagram clone coding)


import { Modal } from "antd";

function Profile(){

const [visible, setVisible] = useState(false);

return(

  <>
    {myposts.map((mypost, index) => {
        return (
          <>
            <img
              key={index}
              className="item"
              onClick={() => {
                setVisible(true);
              }}
              src={`http://localhost:5000/uploads/${mypost.photo}`}
            />
            {visible && (
              <Modal
                title="Basic Modal"
                visible={visible}
                onOk={setVisible(false)}
                onCancel={setVisible(false)}
              >
                <p>Some contents...</p>
                <p>Some contents...</p>
                <p>Some contents...</p>
              </Modal>
            )}
          </>
        );
      })}
    </>
   )}
 

This is the summery of my code. I think when I click image, it should makes modal. But, It doesn't work anything. I don't know which part is wrong. (Modal part has some strange content now. I'll change this part after seeing modal.)


Solution

  • Try to place the modal outside the mypost map, maybe this is why the modal won't show up. You may need another state for the src path of the selected image.

    import { Modal } from "antd";
    
    function Profile() {
      const [visible, setVisible] = useState(false);
      const [selectedImgSrc, setSelectedImgSrc] = useState("");
    
      const imgClick = (imgSrc) => {
        setSelectedImgSrc(imgSrc);
        setVisible(true);
      };
    
      return (
        <>
          {myposts.map((mypost, index) => {
            return (
              <>
                <img
                  key={index}
                  className="item"
                  onClick={() => {
                    imgClick(`http://localhost:5000/uploads/${mypost.photo}`);
                  }}
                  src={`http://localhost:5000/uploads/${mypost.photo}`}
                />
              </>
            );
          })}
    
          <Modal
            title="Basic Modal"
            visible={visible}
            onOk={() => setVisible(false)}
            onCancel={() => setVisible(false)}
          >
            <img src={selectedImgSrc} />
          </Modal>
        </>
      );
    }