229-multi-level-dropdown
229-multi-level-dropdown copied to clipboard
Multiples Errors when using it with Typescript React
When using this code with typescript ans react i get the following errors:
-
Property 'firstChild' does not exist on type 'never'.
-
Type 'null' is not assignable to type 'string | number | (string & {}) | undefined'.
@kappaC0dex have you fixed it?
No not yet working on it
For the first point :
Property 'firstChild' does not exist on type 'never'.
You need to cast firstChild like an HTMLElement
, because firstChild is a ChildNode
and do not contains offsetHeight.
const child = dropdownRef.current?.firstChild as HTMLElement;
const height = child.offsetHeight;
For the second point :
Type 'null' is not assignable to type 'string | number | (string & {}) | undefined'.
Can you tell me which line displays this error message, from memory I had the problem on useRef. If I have the wrong problem, tell me.
You only need to specify the type, in our case it must accept only HTML elements of type Div.
const dropdownRef = useRef<HTMLDivElement>(null);
<div className={styles.dropdown} style={{ height: `calc(${menuHeight}px + 2rem)` }} ref={dropdownRef}>
...
</div>
I also had a type problem on the menuHeight state. To solve this problem, I simply store the number of pixels. and I specify, in the div, the units here in px.
const [menuHeight, setMenuHeight] = useState<number | null>(null);
<div className={styles.dropdown} style={{ height: `calc(${menuHeight}px + 2rem)` }} ref={dropdownRef}>
...
</div>
I hope this has helped you. If you have any questions don't hesitate.