react-select focus() doesn't show cursor after change
See original GitHub issueStackoverflow question: https://stackoverflow.com/questions/58538908/react-select-focus-doesnt-show-cursor-after-change
I’m trying to use ref and focus() to manually set the focus into the control input field. In most instances it works, but not immediately after selecting an Option from the dropdown.
After selecting an option from the dropdown, the control gets the focus but the cursor doesn’t appear. It only appears if you start typing (including hitting the Esc key). On subsequent openings of the menu, the cursor appears along with the focus of the entire control field. Any ideas how to get this working in all situations, including immediately after making a selection?
I’ve created a sample code here: https://codesandbox.io/s/react-select-focus-uk3ic
This is the code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
import styled from "styled-components";
import { stateOptions } from "./data.js";
class PopoutExample extends Component {
selectRef = React.createRef();
state = {
isOpen: false,
option: undefined,
};
toggleOpen = () => {
const isOpening = !this.state.isOpen;
this.setState(
{
isOpen: isOpening,
},
() => isOpening && setTimeout(() => this.selectRef.focus(), 400),
);
};
onSelectChange = option => {
this.toggleOpen();
this.setState({ option });
};
render() {
const { isOpen, option } = this.state;
return (
<Dropdown
target={
<MainButton onClick={this.toggleOpen}>
{option ? option.label : "Select a State"}
</MainButton>
}
>
<Select
menuIsOpen
ref={ref => {
this.selectRef = ref;
}}
styles={{
container: provided => ({
...provided,
display: isOpen ? "block" : "none",
}),
}}
onChange={this.onSelectChange}
options={stateOptions}
value={option}
controlShouldRenderValue={false}
/>
</Dropdown>
);
}
}
const MainButton = styled.button`
padding: 10px;
background-color: aqua;
width: 100%;
`;
const Dropdown = ({ children, target }) => (
<div>
{target}
{children}
</div>
);
ReactDOM.render(<PopoutExample />, document.getElementById("root"));
Issue Analytics
- State:
- Created 4 years ago
- Reactions:13
- Comments:10 (4 by maintainers)
@swiss-chris I think this could be workaround for you![demofixing](https://user-images.githubusercontent.com/16164170/68037723-f0979400-fcfa-11e9-9044-39ba10779ec1.gif)
@namKolo What worked for me was a combination of keeping
menuIsOpen
to true (because I want the dropdown to remember the scroll position), but also addingopenMenuOnFocus
as you suggested ! Thank you very much for this solution 🙏 !!!