Reputation: 361
I am trying to use React.forwardRef() because I am getting the following error in the console if I don't attempt to use it: "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?"
The problem is I am getting a type error which I'm not sure how to resolve when trying to wrap handleDropdownClick in the React.forwardRef() which displays the following error:
I have created an options dropdown using styled-components. I am passing the ref into the 'Dropdown' which is just a top wrapper div with some styling on.
For some context the handleDropdownClick function is responsible for opening and closing the dropdown by using the ref which I have called node. I'm just not sure how to correctly pass the correct type to React.forwardRef, I think that's what its complaining about.
const node = useRef<HTMLDivElement>(null!)
const handleDropdownClick = React.forwardRef((event: MouseEvent, ref) => {
if (node.current.contains(event.target as Node)) return
setdropdownOpen(false)
})
return (
<>
<Dropdown ref={node}>
<DropdownBtn
disabled={disabled}
hasError={hasError}
onClick={() => setdropdownOpen(!dropdownOpen)}
>
{typeSelection}
<ListIcon hasError={hasError} name="chevron" />
</DropdownBtn>
{dropdownOpen && (
<DropdownContent hasError={hasError}>
{options.map((item: any) => {
const isObject = typeof item.value === 'object'
const value = isObject
? item.value['fr-FR']
: item.value
return (
<DropdownItem
typeSelection={typeSelection === value}
onClick={() => handleItemClick(item)}
key={item.index}
>
{value}
</DropdownItem>
)
})}
</DropdownContent>
)}
</Dropdown>
</>
)
Upvotes: 0
Views: 1083
Reputation: 42188
The TypeScript error message mentions void because your handleDropdownClick function doesn’t return any value. A ForwardRefRenderFunction has the same return type as a FunctionComponent — it must return either a JSX.Element or null.
There’s a fundamental misunderstanding here about when and where to use forwardRef. It is used to wrap components, not event handlers.
Your handleDropdownClick should be a simple function which updates the state of dropdownOpen and nothing else. There is no need to forward any ref because the whole component already has access to the node ref variable.
Upvotes: 1