Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Use The MUI Popper Component For Great Interactive Elements

Tooltips and popovers play a crucial role in enhancing the user experience of applications. They provide a convenient way to explain elements or navigate through subsections. They act similarly to breadcrumbs in that they play a crucial role in enhancing user navigation; allowing to display of some content on top of another. Tooltips and popovers are critical for enhancing user experience in applications. They allow further explanation of items when users hover over them and facilitate navigation to subsections through dropdowns.pur

Although tooltips and dropdowns are easy to create with CSS, positioning them to flow seamlessly with the UI can be challenging, usually requiring tedious JavaScript code.

This is where the Material-UI Popper comes in handy. Popper is a component in MUI library that simplifies managing popovers and poppers.

In this article, we will explore the Material-UI Popper component and how it can be leveraged and utilized to create interactive and well-positioned popovers in a React application.

What is Material-UI?

Before diving into the Popper component, let us briefly discuss Material-UI. Material-UI (MUI) is a popular React UI framework that provides a set of pre-designed components following the Material Design guidelines. It simplifies the process of building aesthetically pleasing and responsive user interfaces. It provides you with pre-built robust, customizable, and accessible React components that can be used to build your design system and develop your web applications faster.

MUI was started in 2014 by Hai Nguyen and since then, it has experienced significant growth, boasting 89k+ stars on GitHub, 1.5M+ weekly downloads, with a small bundle size of 93.7kB (Minified+ Gzipped).

The chart below from NPM trends shows a comparison of the number of downloads of Material UI over the last year.

MUI provides one component called Popper that you can use to create a popper in Material-UI.

If you use MUI for your project, consider using Purecode.ai Marketplace to access over 10000+ AI-generated ready-made templates and components to speed up your development process.

Implementing Material UI Popper Component

Now you understand what Material UI library is, its significance, and why it is a preferred choice for most developers. Let us learn how to install React and the MUI library.

Prerequisite

Before creating a Material-UI popper, you need to have the following:

  • NPM is installed on your machine.

  • Basic knowledge of JavaScript and React.

If you need help getting started with React, check out the video tutorial below.

Setting up a React App

In your terminal, enter the following command to create a new React application:

npx create-react-app my-app && cd my-app

Once your app is set up, run the application by entering either of these commands in your terminal:

yarn start

Or using npm:

npm start

Your server should launch in your browser at http://localhost:3000/.

How to Install Material UI

To get set up with MUI we can install it as an NPM package or use Yarn.

npm install @material-ui/core

or

yarn add @material-ui/core

Once the MUI library is successfully installed, you are all set to start using the Material UI components in your React application.

Understanding the Popper

The Material-UI Popper is a powerful tool for creating popover components and tooltips. Unlike standalone tooltip libraries, Popper focuses on positioning and managing popovers effectively within the UI.

Features of Popper

Some important features of the Popper component:

  • 🕷 Popper relies on the 3rd party library (Popper.js) for perfect positioning.
  • 💄 It’s an alternative API to react-popper. It aims for simplicity.
  • 📦 24.9 kB gzipped.
  • The children are Portal to the body of the document to avoid rendering problems. You can disable this behavior with disablePortal.
  • The scroll is not blocked like with the Popover component. The placement of the popper updates with the available area in the viewport.
  • The Popper does not disappear when clicked outside of it. If you require the Popper to hide when clicked elsewhere, you can utilize the ClickAwayListener component as demonstrated in the menu documentation.
  • The anchorEl is passed as the reference object to create a new Popper.js instance.

Setting Up a New Project

In this section, we will walk through the process of setting up a new React project with Material-UI and the Popper component. We will cover project initialization and installing the necessary dependencies.

Project Initialization

To create our React project, we will employ the widely used Create React App.

Run the following command in your terminal, a virtual gateway to the inception of our React journey:

npx create-react-app material-ui-popper-demo
cd material-ui-popper-demo

Installing Material-UI and Dependencies

Install Material-UI and related dependencies:

npm install @mui/material @emotion/react @emotion/styled

Integrating Material-UI Popper

Now that the project is set up, let us integrate Material-UI Popper. We will explore basic usage, styling options, and additional functionalities provided by the Popper.

Basic Usage

Start by importing the necessary components from Material-UI:

// src/index.js

import React from "react";
import ReactDOM from "react-dom";
import { Box } from "@material-ui/core";
import Popper from "@mui/material/Popper"
import "./styles.css";

function App() {

  const [anchorEl, setAnchorEl] = React.useState(null);
  const handleClick = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'simple-popper' : undefined;

  return (
    <Box
      component="section"
      sx={{
        p: 6,
        border: "1px dashed grey",
        backgroundColor: "#9966ff",
        backgroundImage: "url(https://play.tailwindcss.com/img/beams.jpg)",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        height: "450px",
        width: "500px",
        display: "flex",
        flexDirection: "column"
      }}
    >
      <button
        className="btn"
        aria-describedby={id}
        type="button"
        onClick={handleClick}
      >
        Toggle Popper
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl}>
        <Box
          className="tooltip">
          The content of the Popper goes here.
        </Box>
      </Popper>
    </Box>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Add the following styles to the styles.css file.

/* src/styles.css */

.App {
  font-family: sans-serif;
  text-align: center;
}

html,
body {
  background-color: #35454cff;
  color: #fff;
  text-align: center;
}

.btn {
  max-width: 180px;
  border-radius: 8px;
  padding: 8px 12px;
}

.tooltip {
  position: relative;
  border-bottom: 1px dashed #000;
  color: #00aa00;
  margin-top: 8px;
}

This code snippet demonstrates a simple button that, when clicked, triggers the display of a popper with basic content.

Note 📝 The anchorEl is passed as the reference object to create a new Popper.js instance.

Popper demo

Styling the Popper

There are different ways to style the Popper component. You can use the following ways for your styling needs:

  • Custom CSS file (imported into your component): This is the traditional way of writing CSS.

  • Material UI Theme: You can use the ThemeProvider from MUI theme to customize the appearance of popper. If you wish to customize the theme, you need to use the ThemeProvider component in order to inject a theme into your application.

  • Inline styling (CSS-in-JS): This allows you to write CSS properties for components through JavaScript.

In the code snippet above, I made use of the MUI Box component to wrap the popper content. However, Material-UI provides styling solutions through its theming system. You can customize the appearance of the Popper component by leveraging the theming features of Material-UI.

In the code snippet below, I used the Material-UI’s theming system to style the MUI Typography component. To do this, I wrapped the Box component with the ThemeProvider and defined a custom theme using the createTheme function. Here is a code snippet of how you can achieve this:

// src/index.js

import React from "react";
import ReactDOM from "react-dom";
import { Box, ThemeProvider, createTheme, Typography } from "@mui/material";
import Popper from "@mui/material/Popper";
import "./styles.css";

const theme = createTheme({
  typography: {
    primary: {
      fontSize: 12,
      backgroundColor: "#ffcc00", // Your desired background color
      color: "white", // Your desired text color
      padding: "16px", // Your desired padding
      marginTop: "16px", // Your desired margin
    },
  },
});

function App() {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);
  const id = open ? "simple-popper" : undefined;

  return (
    <ThemeProvider theme={theme}>
      <Box
        component="section"
        sx={{
          p: 6,
          border: "1px dashed grey",
          backgroundColor: "#9966ff",
          backgroundImage: "url(<https://play.tailwindcss.com/img/beams.jpg>)",
          backgroundRepeat: "no-repeat",
          backgroundSize: "cover",
          height: "450px",
          width: "500px",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <button
          className="btn"
          aria-describedby={id}
          type="button"
          onClick={handleClick}
        >
          Toggle Popper
        </button>
        <Popper id={id} open={open} anchorEl={anchorEl}>
          <Typography variant="primary">The content of the Popper goes here.</Typography>
        </Popper>
      </Box>
    </ThemeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

MUI-Popper-Styled-with-theme

Additional Functionalities to Customize MUI Popper

The Popper component in MUI provides some props that you can use to customize the behavior, animation, position, and more.

In this section, I will explore the various properties and functionalities offered by the Material-UI Popper, such as positioning options, modifiers, and event handling:

  • open: It is a boolean value. It determines whether the popper should be open or not.

  • anchorEl: It is a function or an element that determines the position of the element.

  • children: It refers to the popper render function or node.

  • components: The components used for the root node. Either a string to use an HTML element or a component.

  • componentsProps:  It refers to the props used for each slot.

  • container: It is a function or an element that will have the portal children appended to it.

  • disablePortal: It is a boolean value. It determines whether the children will be under the DOM hierarchy of the parent component or not. It is false by default.

  • keepMounted: It is a boolean value. It determines whether there to keep the children in the DOM or not. It is false by default.

  • modifiers: It is a function that helps to compute the position of the popper. 

  • placement: It determines the placement of the popper.

  • popperOptions: Different options for the pooper component.

  • popperRef: It is referred to as the used popper ref.

  • slotProps: props used for each slot inside the Popper.

  • slots: It is either a string to use an HTML element or a component, used for each slot inside the Popper.

  • sx: The prop to override and add styles.

  • transition: It is a boolean value. It determines whether there should be any transition or not. It is false by default.

Transitions

The states of the popper can be animated by passing a render prop child and a transition component. These state include: open and close.

This transition component should adhere to the following criteria:

  • Be a direct child descendent of the popper.

  • Call the onEnter callback prop when the enter transition starts.

  • Call the onExited callback prop when the exit transition is completed. These two callbacks allow the popper to unmount the child content when closed and fully transitioned.

Popper has built-in support for react-transition-group.

import * as React from 'react';
import Box from '@mui/material/Box';
import Popper from '@mui/material/Popper';
import Fade from '@mui/material/Fade';

export default function TransitionsPopper() {
  const [open, setOpen] = React.useState(false);
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
    setOpen((previousOpen) => !previousOpen);
  };

  const canBeOpen = open && Boolean(anchorEl);
  const id = canBeOpen ? 'transition-popper' : undefined;

  return (
    <div>
      <button aria-describedby={id} type="button" onClick={handleClick}>
        Toggle Popper
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl} transition>
        {({ TransitionProps }) => (
          <Fade {...TransitionProps} timeout={350}>
            <Box sx={{ border: 1, p: 1, bgcolor: 'background.paper' }}>
              The content of the Popper.
            </Box>
          </Fade>
        )}
      </Popper>
    </div>
  );
}

Customizing the Popper Position

You can use the placement property to customize the position of the Popper element. The supported options are auto-end, auto-start, auto, bottom-end, bottom-start, bottom, left-end, left-start, left, right-end, right-start, right, top-end, top-start, and top.

The example below ⬇ demonstrates how to use the placement props to customize the positioning of the popper element.

import * as React from 'react';
import Box from '@mui/material/Box';
import Popper from '@mui/material/Popper';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Fade from '@mui/material/Fade';
import Paper from '@mui/material/Paper';

export default function PositionedPopper() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [placement, setPlacement] = React.useState();

  const handleClick = (newPlacement) => (event) => {
    setAnchorEl(event.currentTarget);
    setOpen((prev) => placement !== newPlacement || !prev);
    setPlacement(newPlacement);
  };

  return (
    <Box sx={{ width: 500 }}>
      <Popper open={open} anchorEl={anchorEl} placement={placement} transition>
        {({ TransitionProps }) => (
          <Fade {...TransitionProps} timeout={350}>
            <Paper>
              <Typography sx={{ p: 2 }}>The content of the Popper.</Typography>
            </Paper>
          </Fade>
        )}
      </Popper>
      <Grid container justifyContent="center">
        <Grid item>
          <Button onClick={handleClick('top-start')}>top-start</Button>
          <Button onClick={handleClick('top')}>top</Button>
          <Button onClick={handleClick('top-end')}>top-end</Button>
        </Grid>
      </Grid>
      <Grid container justifyContent="center">
        <Grid item xs={6}>
          <Button onClick={handleClick('left-start')}>left-start</Button>
          <br />
          <Button onClick={handleClick('left')}>left</Button>
          <br />
          <Button onClick={handleClick('left-end')}>left-end</Button>
        </Grid>
        <Grid item container xs={6} alignItems="flex-end" direction="column">
          <Grid item>
            <Button onClick={handleClick('right-start')}>right-start</Button>
          </Grid>
          <Grid item>
            <Button onClick={handleClick('right')}>right</Button>
          </Grid>
          <Grid item>
            <Button onClick={handleClick('right-end')}>right-end</Button>
          </Grid>
        </Grid>
      </Grid>
      <Grid container justifyContent="center">
        <Grid item>
          <Button onClick={handleClick('bottom-start')}>bottom-start</Button>
          <Button onClick={handleClick('bottom')}>bottom</Button>
          <Button onClick={handleClick('bottom-end')}>bottom-end</Button>
        </Grid>
      </Grid>
    </Box>
  );
}

Popper-Positioned

Differences Between Material PopOver and Popper

In this section, we will examine the differences between Material PopOver component and Popper. Material UI offers two similar but distinct components for displaying pop-up content – the Popover and the Popper. The scroll and click away are blocked in the PopOver component unlike with the Popper component.

The key differences between them are:

Things to know when using the Popover component:

  • Are modal-like – they block the main content behind them and prevent the user from interacting with anything except the popover

  • Stops page scrolling when open.

  • Close when the user clicks outside of them

  • Behavior: Popovers are used to display supporting content when a user interacts with a trigger. They can also be used to display tooltips, dropdown menus, and other similar elements.

  • Features: Popovers are created on top of the Modal component. They block scroll and click away.

  • Uses: Popovers can be used to notify users about notes they should know before proceeding. They can also be used as a notification to help or guide users.

Things to know when using the Poppers component:

  • Are less disruptive to the user experience. They don’t block interaction with the main content.

  • Allow page scrolling to continue normally when open

  • Do not close when clicking outside. The user has to manually close them.

  • Behavior: Poppers are less intrusive to the user experience. They don’t impose anything on the user and don’t disappear when you click away.

  • Features: Poppers update their placement with the available area in the viewport. They inherit the feature of using a VirtualElement as their anchorEl.

  • Uses: Poppers are used to overlay Material popovers on top of a pressed button or area. They are also used to position elements in an application.

What You Have Learned

In this article, I explored the Material-UI Popper and its application in creating interactive and well-positioned popovers in a React application. I provided an overview of Material-UI, its significance, and the popularity of the MUI library. The article also covered the installation process of React and Material-UI.

A comparison between Material PopOver and Popper components highlighted their differences in behavior, features, and use cases. The article concluded by summarizing the key takeaways, emphasizing the flexibility and customization options offered by Material-UI Popper.

This article serves as a guide to getting started with the Material-UI Popper in a React project. By integrating Material-UI and utilizing the Popper component, you learned that you can create interactive and visually appealing popovers with ease. Experiment with different configurations, styles, and functionalities to enhance the overall user experience in your applications.

You also learned that Popper has inherent support for customization using props such as placement, anchorEl, open*, and more.

Learn more about the supported props from the Popper documentation for a complete reference to all of the props and classes available to the components mentioned here.

Happy coding! 💻

We recently launched our collection of 10,000+ AI-generated custom components for you to choose from for your next web project. Sign up now at Purecode.ai and discover how to 10x your productivity using pre-generated components for MUI, Tailwind CSS, and CSS3.

Best Practices with MUI Popper

Material UI (MUI) is a popular React UI library that uses the Bootstrap and Popper.js libraries under the hood. When using MUI with Popper.js, it is important to keep in mind best practices to ensure smooth performance and maintainability.

Here are some tips:

  • Keep your dependencies up-to-date: Regularly update your React version, MUI version, and Popper.js version to take advantage of the latest features and security patches.

  • Use a build tool: Use a build tool like webpack or parcel to manage your dependencies and bundles.

  • Avoid creating unnecessary re-renders: Avoid unnecessary re-renders by using state checks and conditionals in.

Further Readings

If you enjoyed reading this article, consider checking out other great pieces from our blog.

Check out this YouTube video for even more clarity on the Material-UI Popper ⬇

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.