Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Change a React Bootstrap Component's Position Automatically

In this guide, you will learn how to create a popover component and update its position dynamically.

Nov 9, 2020 • 5 Minute Read

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.

      npx create-react-app react-dynamic-popover

cd react-dynamic-popover

npm start
    

Include React Bootstrap in your basic React app.

      npm install react-bootstrap bootstrap
    

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

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

You can now import bootstrap components, for example:

      import { Button } from 'react-bootstrap';
    

Create PopOver

Copy the sample code below.

      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
    

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.

      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>
    );
}
    

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.

Kimaru Thagana

Kimaru T.

Kimaru is a firm believer of education as a tool of self sufficiency. As software development consultant, living in Kenya, he mainly works to bring small and medium sized business to the internet with custom solutions ranging from data processing to business digitization. Away from the field of coding and computer science, he participates as a mentor for young university students. In his free time, he prefers peace and quiet, away from screens but close to nature.

More about this author