Reputation: 861
My app forms utilize the enter button to tab to specified fields for speed on a ten-key keyboard. When enter is hit, we do a DOM lookup and trigger focus() on the next element. This works great on text fields but I cannot understand how to accomplish this on a Select box in Material UI [email protected]. I can get each of the DOM elements that make up the Select structure, but triggering focus() at any level does nothing. Note: I am able to grab the ref of the item via inputRef on the select to prevent us from traversing the DOM but it still yields no results.
Question on GitHub: https://github.com/callemall/material-ui/issues/9182#issuecomment-345148074
Code Sandbox example: https://codesandbox.io/s/m43qqyo2zy
Upvotes: 2
Views: 6639
Reputation: 21
We need to get to the child div of the Select element that is rendered. It will have 'role' attribute with 'button' as a value. It will also have classes similar to:
To get this div, we can use a callback while passing ref to MUI Select. Here innerRef is the reference being passed to Select Field.
ref={(node) => {
if (node !== null && node.firstChild.getAttribute('role') === 'button') {
innerRef.current = node.firstChild;
} else {
innerRef.current = node;
}
}}
Upvotes: 0
Reputation: 2456
The node
passed to Select.props.inputRef()
references a hidden input
. You would need to focus()
on the div
that is rendered as its sibling. Also, you need to handle the Select
element case first in handleKeyPressInternal()
because getElementsByName()
will return the input
.
This doesn't feel right, though, because you are relying on Select
to render the focusable div
as its immediate sibling. Could be grounds to extend inputRef()
on Select
to return the node that can visually receive focus.
https://codesandbox.io/s/zooz41oo3
Upvotes: 3