Open In App

How to Dismiss a React-Bootstrap Popover on Click Outside ?

Last Updated : 26 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article implements popover functionality using the React Bootstrap library. It consists of a button labelled “Show Popover,” and when this button is clicked, a popover with the title “Popover Right” and the content “Some Amazing Content” is displayed to the right of the button. The popover is shown or hidden based on the state of the “showPopover” variable. The component uses event listeners to detect clicks outside of the popover, allowing it to automatically close when clicked outside.

Web-capture_29-9-2023_105046_loc

Preview Image

Approach

The “PopOver” component in React Bootstrap implements a button trigger to display a popover. It utilises state management to control popover visibility and employs event listeners to detect clicks outside the popover, automatically closing it when necessary. The popover contains a title and content, and the user can modify that according to the requirement by taking references from official documentation. This component offers a user-friendly way to reveal additional information or actions in a popover, making it an interactive UI element for displaying contextual content.

Steps to Create the Application

Step 1: Set up React project using the command

npx create-react-app <<name of project>>

Step 2: Navigate to the project folder using

cd <<Name_of_project>>

Step 3: Install the react-bootstrap library using the following command

npm install react-bootstrap bootstrap

Step 4: Create a folder “components” and add a new file Popover.js that implements the popover feature.

Project Structure

Screenshot-2023-09-28-194139

Project Structure

The updated dependencies in package.json will look like this:

{
"name": "Project Name",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.2",
"react": "^18.2.0",
"react-bootstrap": "^2.9.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}

Example: Write the following code in respective files

Javascript




// App.js
 
import "./App.css";
import
"bootstrap/dist/css/bootstrap.min.css";
import PopOver from
"./components/Popover";
 
function App() {
    return (
        <div>
            <PopOver />
        </div>
    );
}
 
export default App;


Javascript




// PopOver.js
 
import {
    useEffect,
    useState,
} from "react";
import {
    Button,
    Popover,
    OverlayTrigger,
} from "react-bootstrap";
 
export default function PopOver() {
    const [
        showPopover,
        setShowPopover,
    ] = useState(false);
 
    const handleClick = (e) => {
        const buttonElement =
            document.querySelector(
                ".btn"
            );
        if (showPopover) {
            const popoverElement =
                document.querySelector(
                    ".popover"
                );
            if (
                !popoverElement.contains(
                    e.target
                )
            )
                setShowPopover(false);
        } else {
            if (
                buttonElement.contains(
                    e.target
                )
            )
                setShowPopover(true);
        }
    };
 
    useEffect(() => {
        document.addEventListener(
            "mousedown",
            handleClick
        );
        return () => {
            document.removeEventListener(
                "mousedown",
                handleClick
            );
        };
    }, [showPopover]);
 
    return (
        <div>
            <OverlayTrigger
                trigger="manual"
                show={showPopover}
                placement="right"
                overlay={
                    <Popover id="popover-right">
                        <Popover.Header as="h3">
                            Popover
                            Right
                        </Popover.Header>
                        <Popover.Body>
                            <strong>
                                Some
                                Amazing
                                Content
                            </strong>
                        </Popover.Body>
                    </Popover>
                }
            >
                <Button
                    variant="success"
                    className="m-5"
                >
                    Show Popover
                </Button>
            </OverlayTrigger>
        </div>
    );
}


Steps to Run the Application

Step 1: Type the following command in terminal

npm start

Step 2: Open web-browser and type the following URL

http://localhost:3000/

Output:

Recording-2023-09-28-192945

Created Popover using React-BootStrap



Similar Reads

Bootstrap 5 Popovers Dismiss on next click
The popover is an attribute of bootstrap used to make the website look more effective. Popovers are mainly used to display additional information and are displayed with the click of the mouse pointer on a button. Popovers can be dismissed on the user’s next click of a different element than the toggle element by setting the trigger attribute to foc
2 min read
React Suite Popover &lt;Popover&gt; Props
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. To display content specific to a certain topic only when the user performs a certain action Popover comes in handy. Popover Component allows the user to show the popup information that is triggered on some event
3 min read
How to make Bootstrap popover appear/disappear on hover instead of click?
Bootstrap provides in-built support for making popovers. A popover is a content box that appears when a user triggers a specific event with specified element selector. Here, we will discuss methods to trigger popover using "hover" instead of "click". Method 1: Here, we will specify popover trigger in 'hover' using jQuery initialization only. We can
2 min read
How to remove active nav-tab when click outside of nav-tab in Bootstrap ?
Bootstrap has the class called "collapse navbar-collapse" which collapses the navigation bar when the user changes the screen resolution. The java-script along-with it at the bottom of the code triggers the collapsed menu in such a way that when the user clicks the hamburger icon of the menu and navigates to the required link, it again collapses th
2 min read
How to disable click outside modal to close modal in bootstrap ?
Bootstrap is a very powerful, extensible, and feature-packed fronted toolkit which is used to build fast and responsive websites. Bootstrap 5 provides us with its powerful Modal component which can be used to create models within the website at an ease. In this article, we are going to see how we can disable the click outside of the bootstrap modal
4 min read
How to detect click outside React component ?
We can use the createRef() method to create a reference for any element in the class-based component. Then we can check whether click event occurred in the component or outside the component. In the functional component, we can use the useRef() hook to create a reference for any element. Creating React Application And Installing Module: Step 1: Cre
2 min read
How to dismiss the keyboard in React native without clicking the return button ?
In this article, we will see how to dismiss the keyboard in React Native without clicking the return button. To dismiss the keyboard we will be discussing two methods. The first method uses TouchableWithoutFeedback component to invoke a function that dismisses the keyboard whenever the screen is tapped. The second method will use ScrollView along w
2 min read
How to detect click event outside Angular component ?
In angular, clicks are detected by different ways. As click is an event, thus inside a component it is detected by simple event binding. A simple click via event binding for detection within the component is given as follows: @Component({ selector: &quot;geeks&quot;, template: ` &lt;h1 (click)=&quot;clicked()&quot;&gt;{{ some_text }}&lt;/h1&gt; ` }
3 min read
React-Bootstrap Popover Overlay
The React bootstrap provides us with the bootstrap components out of the box compared to normal React. It comes with the pre-applied CSS and the themes and properties of the bootstrap component can be modified by changing the properties. The Dropdown component is used for showing dropdowns in React Bootstrap. The overlay component in React-Bootstra
3 min read
React-Bootstrap Popover Component
React-Bootstrap is a front-end framework that was designed keeping react in mind. Popover Component is a container-type element that hovers over the parent window. It is just like popup information that is trigger on some event over the parent window. We can use the following approach in ReactJS to use the react-bootstrap Popover Component. Popover
2 min read