Search code examples
javascripthtmlreactjsantd

Control Popover antd by button but still keep default behavior


I want to control the Popover Antd using a button, which means I can show and hide the popover by clicking the button. Additionally, I want to retain its default behavior, so when I click on the content, the popover will show up and be hidden when I click outside of it. Thank you so much.


Solution

  • To control the Popover component in Ant Design (Antd) using a button, you can use the visible prop of the Popover to conditionally show or hide it based on the state of a button click. Additionally, to retain the default behavior of showing the Popover when clicking on the content and hiding it when clicking outside, you can use the trigger prop with the value "click" for the Popover.

    App.jsx

    import React, { useState } from 'react';
    import { Button, Popover } from 'antd';
    
    const App = () => {
      const [visible, setVisible] = useState(false);
    
      // Function to toggle the visibility of the Popover
      const handleTogglePopover = () => {
        setVisible(!visible);
      };
    
      // Content to be displayed inside the Popover
      const content = (
        <div>
          <p>This is the content of the Popover</p>
          <p>Clicking inside the Popover won't hide it.</p>
        </div>
      );
    
      return (
        <div>
          <Popover
            content={content}
            visible={visible}
            trigger="click" // Show the Popover on click of the content
            onVisibleChange={(visible) => setVisible(visible)} // Update the state when the visibility changes
          >
            <Button onClick={handleTogglePopover}>Toggle Popover</Button>
          </Popover>
        </div>
      );
    };
    
    export default App;