0

I am working on a project that combines react-datasheet and Material UI Autocomplete to mimic a dropdown inside an Excel cell. The base requirement consists of allowing the user to type in or choose one of the options when the autocomplete gets focus. That is where my problem resides. Because the autocomplete is nested inside a cell, it does not get focus automatically when the parent cell is selected (for example, using the keyboard arrows).

So far, I tried using refs so that I would be able to call .current.focus() using something like the following:

const inputRef = useRef();
useEffect = (() => {
  if (selected) {
    inputRef.current.focus();
  }
}, [selected]);

where selected is a boolean prop that I'm passing from the parent cell to the autocomplete. In other words, I'm trying to somehow make it get focus programatically when selected is true. If you have any tips or ideas to get this to work, or another potential approach I could investigate, I would appreciate it.

EDIT: Here's the component tree as shown in the React Dev Tools. Upon inspecting the autocomplete, it does not expose a focus() method. I see there are inputs down the tree but I am not clear on how I can call focus on them and if that would cause the autocomplete to get focus.

enter image description here

  1. The parent (actually, ancestor) cell component. Here's where I have the selected prop.
  2. The Material UI Autocomplete.
  3. Inputs
newdev
  • 109
  • 2
  • 9
  • What is `inputRef` ? If it is the autocomplete component, `inputRef.current.focus()` may not have the effect you're looking for. You'll have to find the actual `` element and call focus on that. For example: `inputRef.current.querySelector('input').focus()`. – Titus Dec 05 '20 at 12:40
  • @Titus I edited my question. Please let me know if I am explaining myself correctly or if you need further info. I only obfuscated the components that have a name related with the company or the project itself. – newdev Dec 05 '20 at 13:38

1 Answers1

2

@newdev I ran into the same issue and @Dekel's answer here helped solve the mystery: react material ui autocomplete element focus onclick.

TLDR: You need to add the ref to the TextField element in Autocomplete's renderInput prop.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Fabio B
  • 36
  • 1