Build Reusable Popover Component in React
If you are learning React, you might be familiar with the concept of reusable components. In this article, we will discuss how to build a reusable popover component in React.
Step 1: Create the Popover Component
First, we need to create a new React component called Popover. This component will render a popover that can be used to display additional information or options.
import React from 'react';
const Popover = ({ children, content }) => {
const [showPopover, setShowPopover] = React.useState(false);
const handlePopover = () => {
setShowPopover(!showPopover);
}
return (
<>
{children}
{showPopover && {content}}
>
)
}
export default Popover;
Step 2: Using the Popover Component
Once the Popover component is created, we can use it in our React application to display popovers wherever needed. Here is an example of how to use the Popover component:
import React from 'react';
import Popover from './Popover';
const App = () => {
return (
)
}
export default App;
Step 3: Styling the Popover
Finally, we can add some CSS to style the popover however we like. Here is an example of how to style the popover:
.popover {
position: absolute;
background-color: #fff;
box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2);
padding: 10px;
z-index: 9999;
}
By following these steps, you can build a reusable popover component in React that can be used throughout your application. This will help you keep your code DRY and make it easier to maintain and update your application in the future.
很棒,感谢
Is it possible to do without using cloneElement? React documentation does not recommend it because, quote: "Cloning children makes it hard to tell how the data flows through your app".
is there a way to make the popover not fixed, but next to the Popover.Trigger when scrolling?
Can you please share how you would merge `onClick` and `ref` in trigger? Thanks in advance!
Focus ring color is black in stackblitz, not blue. Thanks for this! Making accessible component is tough.
Would love to see more content like this😁