1

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
2
  • 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 <input/> element and call focus on that. For example: inputRef.current.querySelector('input').focus(). Commented Dec 5, 2020 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. Commented Dec 5, 2020 at 13:38

1 Answer 1

3

@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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, @Fabio B! That did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.