简体   繁体   中英

React MUI customizing Autocomplete's Popper component

I'd like to customize the width of the Popper which comes with the Autocomplete component. In my case the Autocomplete component it is placed inside a parent component, alongside a TextField.

Here the snippet on Codesandbox:

编辑 BasicTextFields 材质演示(分叉)

At the moment I have the following: 在此处输入图像描述

The parent component background color is set to green.

MY GOAL: the Autocomplete Popper component should cover the entire green area , in other words, the entire area delimited by the parent component (as consequence of this also the TextField).

EDIT 1: after Amr Eraky answer (solving the width problem) 在此处输入图像描述

EDIT 2: So, the expected behaviour is the following (sorry for my poor graphic skills, I hope it is understandable anyway):

真实的预期行为

So, we've got 2 problems here:

  1. The width
  2. The placement

As for the width I am able to set a custom width with the following code:

    const PopperMy = useCallback((props) => {
        return (<Popper {...props} style={{ width: 350 }} placement='right-end' />)
    },
 []);

But as you can see, this is not responsive and it is not even bound in some way to the width of the parent component, so this is not a good approach.

As for the placement, I'd like the popper to overlap its parent, but in the placement options I cannot find something like this, every option never allows the overlapping.

Could you please suggest a way to address these issues?

You should use anchorEl prop of Popper to set the position of the popper.

anchorEl : Type of : HTML element | object | func
An HTML element, virtualElement, or a function that returns either. It's used to set the position of the popper. The return value will passed as the reference object of the Popper instance.

You can get anchorEl of any element using useRef ,
But because of your anchor element is in other component you can use id
And set height of Popper equal to anchorEl 's height.

const PopperMy = React.useCallback((props) => {
    const anchorEl = document.getElementById('new1');   // Or any other element
    return <Popper {...props} anchorEl={anchorEl} style={{ width: anchorEl.clientWidth }} placement='bottom' />;
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM