Unable to set focus to React ComboBox component
See original GitHub issueWhat package(s) are you using?
-
carbon-components
-
carbon-components-react
Summary
Generally with React we would set focus on a component by getting a ref
to the component and calling the focus
function on the current ref. Unfortunately, there is no forwardRef
and we have no way to get a ref
to the input
within the ComboBox
. I can’t seem to figure out a way to inject anything in via props. Is there some way to make this happen?
Relevant information
An example of what I am trying to do:
const Example = () => {
const [adding, setAdding] = useState(false);
return (
<>
<Button
onClick={() => {
setAdding(true);
// HACK to set focus
setTimeout(
() => document.getElementById("test").focus(),
100 // YMMV *shrug*
);
}}
/>
<ComboBox
className={classNames({ [styles.hide]: !adding })}
downshiftProps={{ isOpen: true }}
id="test"
onChange={() => setAdding(false)}
items={[]}
/>
</>
)
}
Basically, when the user clicks a Button the ComboBox will show with the dropdown portion visible. I would also like the text input to have focus so the user can start typing right away. You can see I’m using a setTimeout
to manually wait for the box to appear so I can set focus to it. Would love some other more reliable method. Suggestions?
Issue Analytics
- State:
- Created 4 years ago
- Comments:14 (7 by maintainers)
Top Results From Across the Web
Not able to set focus on the Dropdown component in Primereact
I am trying to set focus on "Dropdown" component of the primereact but focus is not coming to the "Dropdown" component.
Read more >Initializing focus state in React: you might be doing it wrong
Initializing focus state in React: you might be doing it wrong. Have you ever written a component with internal state like hasFocus or...
Read more >How to Set the Read-only TextBox in React TextBox component
You can make the TextBox as read-only by setting the readonly attribute to the input element. Source. Preview.
Read more >How to set focus for input field of dropdown element-Reactjs
Coding example for the question React semantic UI: How to set focus for input field of dropdown element-Reactjs.
Read more >Combobox - Lightning Design System
When an option from the listbox is "in focus", user focus never leaves the input field, since we manually create a programmatic or...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@supermonkeybrainz converted to code sandbox https://codesandbox.io/s/sweet-bush-kkb65
Got it, thanks for the example!