How to render a React component inside a Bootstrap popover
If we want our React component’s content to appear inside the Bootstrap popover, we need to render the component inside the Bootstrap popover.
We’ll follow a simple example to understand the rendering of a React component inside a Bootstrap popover. Here’s a step-by-step explanation:
Steps
We first create the component we want to render in Bootstrap popover. For this, we create a
componentsfolder inside thesrcfolder of our React application. We then create a file namedPopoverContent.jsinside thesrc/componentsfolder. Here’s what thePopoverContent.jsfile contains:
const MyComponent = () => {return <div>This is a sample content that will appear in the popup when button is clicked.</div>;};export default MyComponent;
Next, we import this component inside the
App.jsfile of our React application so that we can render it there.
import MyComponent from './components/PopoverContent'
Then, we create a simple Bootstrap popover in the
App.jsfile. For this, we need to import theOverlayTriggerandPopovercomponents.OverlayTriggeris not a standalone component and is used with Bootstrap popover and tooltip. It wraps any target element, for example, a button. When it interacts with this target element, it triggers the display of a Bootstrap popover or tooltip. So, to create a popover, we use<OverlayTrigger/>and inside itsoverlayproperty, we render the Bootstrap’s popover component using the<Popover></Popover>tag.
import React from 'react';import 'bootstrap/dist/css/bootstrap.min.css';import { OverlayTrigger, Popover} from 'react-bootstrap';import MyComponent from './components/PopoverContent'function App() {return (<div><OverlayTrigger trigger="click" placement="right" overlay={<Popover></Popover>}></OverlayTrigger></div>);}export default App;
We render
MyComponentinside<Popover></Popover>because we want our component’s content to appear inside the Bootstrap popover.
function App() {return (<div><OverlayTrigger trigger="click" placement="right" overlay={<Popover><MyComponent/></Popover>}></OverlayTrigger></div>);}export default App;
Note that
<OverlayTrigger/>has atrigger='click'property. It means that popover is triggered only when a button is clicked. So, we create a button wrapped inside<OverlayTrigger/>.
Note: We can use multiple other options, such as hover, focus, manual, etc., instead of click in the trigger property. click is just used as an example to show the content of the rendered component inside the popover when a button is clicked.
function App() {return (<div><OverlayTrigger trigger="click" placement="right" overlay={<Popover><MyComponent/></Popover>}><button>Click me</button></OverlayTrigger></div>);}export default App;
Code
Here’s the complete executable code of the example followed above:
import React from 'react';
const MyComponent = () => {
return <div>This is a sample content that will appear in the popup when button is clicked.</div>;
};
export default MyComponent;Free Resources