Pular para o conteúdo

Unstyled popper

The PopperUnstyled component lets you create tooltips and popovers that display information about an element on the page.

Introduction

PopperUnstyled is a utility component for creating various kinds of popups. It relies on the third-party library (Popper.js v2) for positioning.

Component

Usage

After installation, you can start building with this component using the following basic elements:

import PopperUnstyled from '@mui/base/PopperUnstyled';

export default function MyApp() {
  return <PopperUnstyled>{/* the popper's content */}</PopperUnstyled>;
}

Basics

By default, the popper is mounted to the DOM when its open prop is set to true, and removed from the DOM when open is false.

anchorEl is passed as the reference object to create a new Popper.js instance. The children are placed in a Portal prepended to the body of the document to avoid rendering problems. You can disable this behavior with disablePortal prop.

The following demo shows how to create and style a basic popper. Click Toggle Popper to see how it behaves:

import * as React from 'react';
import PopperUnstyled from '@mui/base/PopperUnstyled';
import { styled, Theme } from '@mui/system';

const StyledPopperDiv = styled('div')(
  ({ theme }: { theme: Theme }) => `
  padding: 0.5rem;
  border: 1px solid;
  background-color: ${theme.palette.mode === 'dark' ? '#121212' : '#fff'};
  opacity: 1;
  margin: 0.25rem 0px;
`,
);

export default function SimplePopper() {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

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

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

  return (
    <div>
      <button aria-describedby={id} type="button" onClick={handleClick}>
        Toggle Popper
      </button>
      <PopperUnstyled id={id} open={open} anchorEl={anchorEl}>
        <StyledPopperDiv>The content of the Popper.</StyledPopperDiv>
      </PopperUnstyled>
    </div>
  );
}

Customization

Placement

The popper's default placement is bottom. You can change it using the placement prop. Try changing this value to top in the interactive demo below to see how it works:

Placement value:
ANCHOR

Transitions

You can animate the open and close states of the popper with a render prop child and a transition component, as long as the component meets these conditions:

  • Is a direct child descendent of the popper
  • Calls the onEnter callback prop when the enter transition starts
  • Calls 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.