Home > other >  Is it possible to open an antd image preview with a button?
Is it possible to open an antd image preview with a button?

Time:12-17

I want to open the preview of an Image in antd without clicking on the image thumbnail itself (e.g. by clicking on a button):

import React from 'react';
import {Image, Button} from 'antd';

const Foo: React.Fc<any> = (props) => {

const [isPreviewVisible,setPreviewVisible] = useState<boolean>(false);

return (
  <div>
       <Image 
        // something like this 
        // isPreviewVisible={isPreviewVisible} 
        src="some url"
       />
       <Button onClick={()=>setState(!isPreviewVisible)}>Click me!</Button>
  </div>
  );
};

I would like to implement it similar to the code above, but could not find any way to do it.

Edit: I want to control/toggle the visibility of the preview with a state.

CodePudding user response:

You can do it like this:

function ImageDemo() {
  const [isPreviewVisible, setPreviewVisible] = useState(false);
  return (
    <>
      <Image
        width={200}
        preview={{
          visible: isPreviewVisible,
          onVisibleChange: (visible, prevVisible) => setPreviewVisible(visible),
        }}
        src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
      />
      <Button onClick={() => setPreviewVisible(!isPreviewVisible)}>
        Click me
      </Button>
    </>
  );
}

I've also implemented an example here you can check it out:

  • Related