How to I keep a Material-ui Select open when I click on only one of the items in it - reactjs

I have been writing a custom Material-UI Select dropdown which has an optional text field at the top to allow the user to search / filter items in the Select if there were many entries.
I am struggling with how to keep the Select open when I click on the text field (rendered as an InputBase) and just have the normal behavior (of closing the Select when a regular MenuItem is selected.
CodeSandbox here : https://codesandbox.io/s/inspiring-newton-9qsyf
const searchField: TextField = props.searchable ? (
<InputBase
className={styles.searchBar}
onClick={(event: Event) => {
event.stopPropagation();
event.preventDefault();
}}
endAdornment={
<InputAdornment position="end">
<Search />
</InputAdornment>
}
/>
) : null;
return (
<FormControl>
<Select
className={styles.root}
input={<InputBase onClick={(): void => setIconOpen(!iconOpen)} />}
onBlur={(): void => setIconOpen(false)}
IconComponent={iconOpen ? ExpandMore : ExpandLess}
{...props}
>
{searchField}
{dropdownElements.map(
(currEntry: string): HTMLOptionElement => (
<MenuItem key={currEntry} value={currEntry}>
{currEntry}
</MenuItem>
)
)}
</Select>
</FormControl>
);
As you can see above I've tried using stopPropagation and preventDefault but to no avail.

check out this codesandbox link: https://codesandbox.io/s/busy-paper-9pdnu
You can use open prop of Select API

I was able to make a controlled open select by providing open prop as a react state variable and implementing correct event handlers. To make it controlled you must provide onOpen and onClose props of the Select and make sure the open prop stays true when the custom textfield is clicked.
One more important thing I had to do was override the default keyDown behavior of the Select component. If you open up a Select and start typing into it, it shifts focus to the select option that matches what you are typing. For example, if you Select had an option with the text Foobar and if you start typing Food and water, it would cause focus to shift from your custom text input onto the Foobar option. This behavior is overridden in the onKeyDown handler of the custom textfield
Working sandbox here
Edit: even though this worked in the codepen, I had to add onChange={handleOpen} to the Select as well to get it working on a real browser with React and Next.

You can still use stopPropagation to make it work
// open state
const [isSelectorOpen, setisSelectorOpen] = useState(false)
// handle change
const handleChange = event => {
const { value } = event.target
event.stopPropagation()
// set your value
}
// selector
<Select
multiple
open={isSelectorOpen}
onChange={handleChange}
input={(
<Input
onClick={() => setisSelectorOpen(!isSelectorOpen)}
/>
)}
// other attribute
>
<MenuItem>a</MenuItem>
<MenuItem>b</MenuItem>
<MenuItem>c</MenuItem>
</Select>

In my case, none of the above worked, but this did the trick to stop closing the Select:
<MenuItem
onClickCapture={(e) => {
e.stopPropagation();
}}>
You can also change onMouseEnter to change some default styling that comes with using MenuItem (like pointer cursor when mouse enters its layout)
onMouseEnter={(e) => {
e.target.style.backgroundColor = "#ffffff";
e.target.style.cursor = "default";
}}
In my case i also needed to remove the grey clicking effect that MenuItem makes on click, which is a new object generated in MuiTouchRipple-root, so changing display to none did the trick.
sx={{
"& .MuiTouchRipple-root": {
display: "none",
},
}}

Related

react-select doesn't play well in mobile when dropdown icon is "overridden" and onMenuOpen+onMenuClose are used

I am using react-select for value input in my web app. I have to override dropdown indicator icon according to design and some dynamic modifications has to be performed depending on the opened/closed status of the menu. I am using styled-components and I have simplified the code a bit to be presented here:
const DropdownIndicator = (props) => {
return (
<components.DropdownIndicator {...props}>
</components.DropdownIndicator>
);
};
<S.InputField
disabled={disabled}
labelLeft={labelLeft}
noLabel={!label}
className={className}
fieldType={state?.type}
inputType={state?.inputType}
notClearable={notClearable}
extendOnOpen={extendOnOpen && menuIsOpen}
menuIsOpen={menuIsOpen}
menuHeight={menuHeight}
>
<label htmlFor={id}>{label}</label>
<div className="input-wrapper">
<Select
id={id}
placeholder={'test'}
components={{ DropdownIndicator }}
// menuIsOpen={menuIsOpen}
onMenuOpen={() => {
console.log('menu opened');
setMenuIsOpen(() => true);
}}
onMenuClose={() => {
console.log('menu closed');
setTimeout(() => setMenuIsOpen(() => false), 3000);
}}
/>
</div>
</S.InputField>
Now, when I try to open the menu clicking on the Select's control field, the menu opens as expected, but when I want to open it clicking on the dropdown icon, the operation becomes hardly predictable - basically I get the 'menu opened' and 'menu closed' directly after, so menu doesn't stay open. Why could that be? Is it a bug in the react-select design?
The funny thing is, if I comment either components={{ DropdownIndicator }} or one of onMenuOpen or onMenuClosed, the menu opens/closes as expected, but never when both ("overridden" DropdownIndicator and onMenuOpen/onMenuClosed) are employed. And I put "overridden" in quotes as it is not technically overridden (I've removed the icon change from <components.DropdownIndicator {...props}></components.DropdownIndicator> as it doesn't impact the outcome), it's actually mimicking (as I understand) the default behaviour of react-select's menu flow.
Important! It only happens in mobile resolutions. Desktop res works just fine. So my understanding this has got something to do with onFocus/onBlur and the way they are treated in touch devices.
Any thoughts?

Material UI Popper over TextField how to keep popper open if the popper options are selected

I am using React Material UI, and I have a Textfield which if I focus on it will deploy a Popper with a simple Menu. If the Textfield loses the focus then the Popper closes itself. The thing is I need to select any option from the menu without close the Popper, but when I do that the Textfield loses the focus. What I need is to keep the Popper on only if I click outside of the Textfield or the Menu.
Everything is on this codesandbox.
I tried this:
const selected = prop => {
console.log(prop);
}
...
<Paper elevation={3} className={classes.paper}>
<MenuList>
<MenuItem onClick={() => selected('first')}>
First Option
</MenuItem>
<MenuItem onClick={() => selected('next')}>
Next Option
</MenuItem>
<MenuItem onClick={() => selected('last')}>
And Last Option
</MenuItem>
</MenuList>
</Paper>
</Popper>
Also tried with ClickAwayListener wrapping both components, the TextField and the Popper:
<ClickAwayListener onClickAway={blur}>
<>
<TextField ... />
<Popper ...>
...
</Popper>
</>
</ClickAwayListener>
Unsuccessfully both times... How can I achieve this?
Although the solution by #Dekel is working well enough.
But in my opinion, it would be better if we would use React.useRef() for focusing on the text field.
Here is the updated solution link:
https://codesandbox.io/s/goofy-frost-bb88l?file=/src/MyApp.js
const textFieldRef = React.useRef();
Inside return ()
<TextField
aria-describedby={id}
onFocus={focus}
onBlur={blur}
placeholder="Focus on me"
inputRef={textFieldRef}
/>
On selecting any menu list item
const selected = event => {
console.log("Selected ", event.target.innerText);
textFieldRef.current.focus();
};
I think it's best to implement this using the Autocomplete, but since the OP requested another solution - here is another option:
Once blur - check the element that caused the blur. If that element is one of the items in the popper - don't blur:
if (e.relatedTarget && e.relatedTarget.classList.contains("MuiListItem-root")) {
return;
}
The full blur function will look like this:
const blur = (e) => {
if (e.relatedTarget && e.relatedTarget.classList.contains("MuiListItem-root")) {
e.target.focus();
return;
}
setAnchorEl(null);
};

How to customize clear behaviour of Material-UI Autocomplete?

I have a controlled Autocomplete component bound to a state prop from redux, that's all working. The onChange event is fired when the user clicks the "clear" icon, however the input is focused and the dropdown opens when this occurs.
How can I prevent the input focus / dropdown open only when the selected option is cleared? My preferred behaviour would be for it to return to having "null" selected and showing the label un-shrunk.
The code looks roughly like this. value is sourced from mapStateToProps, onChange comes from mapDispatchToProps.
const LetterSelect: FC<Props> = ({ value, onChange }: Props) => {
return (
<Autocomplete
options={["A", "B", "C", "D"]}
value={value ?? null}
onChange={(e,v) => onChange(v)}
renderInput={params => (
<TextField {...params} label="Letter" variant="outlined" fullWidth />
)}
/>
)
}
Sorry I didn't get back to this sooner: there actually wasn't a direct fix for this.
Instead, I opened an issue on the Github and it was agreed to change the default behaviour - refer to this PR.
Clicking the Clear icon no longer opens the Autocomplete as of v4.8.1

react-select add a search input inside the MenuList

I'm using react-select (https://react-select.com) and I'm trying to add a search input inside the MenuList itself (at the top) instead of the default behaviour of searching from the Container.
<Select
...
components={{
...
MenuList: (props: any) => {
return (
<components.MenuList {...props}>
<div className="search-wrapper">
<input
value={search}
onChange={searchChange}
placeholder="Search"/>
</div>
{props.children}
</components.MenuList>
);
},
}}
>
</Select>
It's working and I get a nice input in the top of my menu:
but the input seems to be disabled. (adding disabled=false to the input doesn't effect anything)
any idea of that? why it's happens?
what is the correct way to implement such feature?
This variant works for me.
First you should remove innerProps prop from components.Menu.
I didn't try with components.MenuList, but I guess it should works too.
<components.MenuList {...props} innerProps={undefined}>
Then you will be able to use input, but menu will close on every click, so:
Second you should control menu state with menuIsOpen prop.
first you can override SelectContainer:
const SelectContainer: React.FC<CommonProps<object, false>> = ({ children, ...props }) => (
<components.SelectContainer {...props}>
<div onClick={() => setMenuOpen(true)}>
{children}
</div>
</components.SelectContainer>
);
Then add a handler to close menu on click inside menu.

Ant Select closes dropdown

I am using Ant Select component inside Dropdown component. Here is my index file which renders Dropdown
const getMenu = filter => (
<MenuContainer
...
/>
);
<Dropdown
overlay={getMenu(searchFilter)}
trigger={['click']}
visible={this.state.search}
onVisibleChange={val =>
this.handleDropdownVisibility(val, searchFilter)
}
>
...
</Dropdown>
Here is my MenuContainer which return Select Component inside it
handleSelectChange = val => {
this.setState({
selectedValue: val,
});
};
<Select
ref="selectBox"
onChange={this.handleSelectChange}
style={{ width: '100%' }}
>
{numberComparision.map((item, i) => {
return (
<Option key={i} value={item.id}>
{item.name}
</Option>
);
})}
</select>
so on clicking select value onVisibleChange fires and closes dropdown
In current v3.3.1 there is no API to prevent to close the Dropdown list.
As a solution I can offer this custom component.
Item has a property clickable which indicates will be the droplist closed after click or not. You can set true/false or css name of an element which should not trigger closing drop-list.
Change Menu.Item where the select is contained to a Menu.ItemGroup, those do not trigger the onVisibleChange when clicked.
You are mixing components that are not meant to be mixed here, I believe.
Dropdown expects its overlay to be a menu of some sorts. Or at least something static that does not open yet another dynamic <div> layer.
Select already has a dropdown type behaviour. So your Dropdown opens the Select which opens the Select dropdown, and then they both react to the click event and close.
It is currently not clear from your question and screenshot what you are actually trying to achieve, that could not be achieved using just a Select. You could try clarifying that.

Resources