Search code examples
material-uidatepicker

Controlling position of MUI Datepicker v6 popover in absence of textField


I'm rendering a Datepicker without a text field and it's getting positioned in the upper left hand corner of the screen no matter what slotProps popper properties I pass in to position it. From other posts, I understand that the problem is that it anchors the popover on the text field and in the absence of a text field, it positions it in the upper left of the screen.

From other posts, I gather than I might solve this with a custom TextField, but I'm not sure what form that should take or if there is a simpler or more idiomatic solution. Any help would be appreciated.

Here's code and a sandbox which demonstrates the problem:

import React, { useState } from "react";
import { DemoContainer } from "@mui/x-date-pickers/internals/demo";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";

export default function BasicDatePicker() {
  const [open, setOpen] = useState(false);
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <div
        style={{
          display: "flex",
          justifyContent: "center",
        }}
      >
        <DemoContainer components={["DatePicker"]}>
          <button onClick={() => setOpen(!open)}>
            Toggle Calendar Open/Closed
          </button>
          <DatePicker
            open={open}
            onClose={() => {
              setOpen(false);
            }}
            slots={{ textField: () => null }}
          />
        </DemoContainer>
      </div>
    </LocalizationProvider>
  );
}

As a related aside, the AI bots that I've asked about this seem only to be knowledgeable about v5.


Solution

  • For v7, you can specify the position of the DatePicker calendar by using the slotProps property as follows:

                    slotProps={{
                        popper: {
                            anchorEl: document.getElementById('event-icon'),
                        },
                    }}
    

    Sorry, but I can't recall where I found this detail. You can, of course, use whatever you want for the anchorEl value.