Author avatar

Kimaru Thagana

Change a React Bootstrap Component's Position Automatically

Kimaru Thagana

  • Nov 9, 2020
  • 5 Min read
  • 46 Views
  • Nov 9, 2020
  • 5 Min read
  • 46 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

During design and development of frontend interfaces in React.js, you will come across instances where you need to display information once a user clicks or hovers on an item. A popover is a useful tool for this scenario. It's similar to a tooltip, but the difference is that a popover can provide more content.

In this guide, you will learn how to create a popover component. You will also learn how to update a popover's position dynamically. The popover component used in this guide is from React Bootstrap. The guide assumes that you have basic (beginner level) knowledge of React.js.

Go ahead and set up your application.

Set Up Sample App

Open your terminal and run these commands to create a basic React app.

1
2
3
4
5
npx create-react-app react-dynamic-popover

cd react-dynamic-popover

npm start
bash

Include React Bootstrap in your basic React app.

1
npm install react-bootstrap bootstrap
bash

In your app.js file, include the stylesheet as well.

1
import 'bootstrap/dist/css/bootstrap.min.css';
js

You can now import bootstrap components, for example:

1
import { Button } from 'react-bootstrap';
js

Create PopOver

Copy the sample code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const popover = (
    <Popover id="popover-basic">
        <Popover.Title as="h3">Popover</Popover.Title>
        <Popover.Content>
            Hello popover
        </Popover.Content>
    </Popover>
);

function App() {
    return (
    <OverlayTrigger trigger="click" placement="right" overlay={popover}>
        <Button variant="success">Click here</Button>
    </OverlayTrigger>
);
}
export default App
js

Overlays are fundamental components for tooltips and popovers. Overlays add support for transitions and toggling visibility. The code above creates a simple popover that pops up when a user clicks the button. You can place the popover component in different positions according to your preferences, i.e., top,bottom, etc. via the placement prop.

In the next example, you will create a popover that repositions itself with respect to changes in content.

Go ahead and copy the sample code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const UpdatingPopover = React.forwardRef(
    ({ popper, children, show: _, ...props }, ref) => {
        useEffect(() => {
            console.log('updating!');
            popper.scheduleUpdate();
        }, [children, popper]);

        return (
            <Popover ref={ref} content {...props}>
                {children}
            </Popover>
        );
    },
);

const description = `
  'React is an open-source, front end, JavaScript library for building user interfaces or UI components.
      It is maintained by Facebook and a community of individual developers and companies.'
`;
const summary = 'React is Cool';

function App() {
    const [content, setContent] = useState(summary);

    useEffect(() => {
        const timerId = setInterval(() => {
            setContent(content === summary ? description : summary);
        }, 3000);

        return () => clearInterval(timerId);
    });

    return (
        <OverlayTrigger
            trigger="click"
            placement="bottom"
            overlay={
                <UpdatingPopover id="popover-contained">{content}</UpdatingPopover>
            }
        >
            <Button>click me</Button>
        </OverlayTrigger>
    );
}
js

Making a popover reposition itself every time the size changes requires manual input. In this case, React Bootstrap provides a nifty function called scheduleUpdate, which works with the popper prop. This method is used by the overlay component to reposition itself.

In our example, the popover updates content after a three-second interval once the button is clicked. You then pass content to be rendered from the parent component in UpdatingPopover to its child Popover. This is made possible by React's forwardRef. You can learn more about forwarding refs at the React.js site. In the function UpdatingPopover, you also pass the popper prop and ref to the Popper component, which is rendered on our page. To better understand this approach, the sample code provides a log of every time the content is updated in the popper.

Conclusion

The guide enables you to further build on your frontend skills as a developer. To explore more on this topic. please check out more components at the React-Bootstrap site.

0