Creating a custom popover in React enhances user interaction by displaying additional content or controls in a floating layer. Here's a step-by-step guide to building a simple, accessible popover component:
1. Set Up Your React Project:
If you haven't already, create a new React application:
npx create-react-app react-popover
cd react-popover
2. Create the Popover Component:
Define a Popover component that manages its visibility and positioning.
import React, { useState, useRef, useEffect } from 'react';
import './Popover.css'
const Popover = ({ children, content }) => {
const [isVisible, setIsVisible] = useState(false);
const popoverRef = useRef(null);
const triggerRef = useRef(null);
const toggleVisibility = () => {
setIsVisible(!isVisible);
};
useEffect(() => {
const handleClickOutside = (event) => {
if (
popoverRef.current &&
!popoverRef.current.contains(event.target) &&
!triggerRef.current.contains(event.target)
) {
setIsVisible(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
return (
<div className="popover-container">
<button
ref={triggerRef}
onClick={toggleVisibility}
className="popover-trigger"
aria-haspopup="true"
aria-expanded={isVisible}
aria-controls="popover-content"
>
{children}
</button>
{isVisible && (
<div
id="popover-content"
ref={popoverRef}
className="popover-content"
role="dialog"
aria-modal="true"
>
{content}
</div>
)}
</div>
);
};
export default Popover;
3. Style the Popover:
Add CSS to position and style the popover.
.popover-container {
position: relative;
display: inline-block;
}
.popover-trigger {
background-color: #007bff;
color: white;
border: none;
padding: 10px;
cursor: pointer;
border-radius: 4px;
}
.popover-content {
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
margin-top: 10px;
background-color: white;
border: 1px solid #ccc;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
border-radius: 4px;
padding: 15px;
z-index: 1000;
white-space: nowrap;
}
4. Use the Popover Component:
Implement the Popover component in your main application file.
import React from 'react';
import Popover from './Popover';
import './App.css';
function App() {
return (
<div className="App">
<h1>Custom Popover Component</h1>
<Popover content={<div>This is the popover content!</div>}>
Click Me
</Popover>
</div>
);
}
export default App;