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>
</>
)
