What Typescript type to require for useRef in AsyncSelect #4669
-
This is specifically a question about using react-select with Typescript, and I'm pretty new to both. All suggestions are appreciated! For reference, I'm using these packages: "react-select": "^4.3.1",
"@types/react-select": "^4.0.15", I'm trying to pass a ref to my AsyncSelect so I can later call If I don't type the ref when initializing, I get const SearchBar = (props: Props): JSX.Element => {
const ref = useRef(null);
...
return (
<SearchForm>
<AsyncSelect
{...all my options here}
ref={ref}
/>
<ClearSearchButton
aria-label="Clear Ratings Search"
type="button"
onClick={() => {
clearSearchInput();
if (ref.current) {
ref.current.focus(); \\ `Object is possibly null`
}
}}
/>
</SearchForm> If I try to initialize the ref with a type of AsyncSelect, it requires I specify my custom option type, but doing so throws an error, like it's expecting me to instantiate the selector right then: const SearchBar = (props: Props): JSX.Element => {
const ref = useRef<AsyncSelect<SelectOption>(null); // `Value of type 'typeof Async' is not callable. Did you mean to include 'new'?`
...
return (
<SearchForm>
<AsyncSelect
{...all my options here}
ref={ref}
/>
<ClearSearchButton
aria-label="Clear Ratings Search"
type="button"
onClick={() => {
clearSearchInput();
if (ref.current) {
ref.current.focus(); \\ `Property 'current' does not exist on type 'boolean'.`
}
}}
/>
</SearchForm> I did some digging through the node package for react-select trying to figure out where I'm going wrong. Our TS config doesn't allow |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Typing it this way works for me:
|
Beta Was this translation helpful? Give feedback.
-
you can use this with useRef:
|
Beta Was this translation helpful? Give feedback.
Typing it this way works for me:
CodeSandbox