229-multi-level-dropdown icon indicating copy to clipboard operation
229-multi-level-dropdown copied to clipboard

Multiples Errors when using it with Typescript React

Open jvkonstantin opened this issue 4 years ago • 3 comments

When using this code with typescript ans react i get the following errors:

  1. Property 'firstChild' does not exist on type 'never'.

  2. Type 'null' is not assignable to type 'string | number | (string & {}) | undefined'.

jvkonstantin avatar Dec 27 '20 15:12 jvkonstantin

@kappaC0dex have you fixed it?

hansfpc avatar Feb 19 '21 04:02 hansfpc

No not yet working on it

jvkonstantin avatar Mar 02 '21 07:03 jvkonstantin

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.

Hardel-DW avatar Mar 21 '22 20:03 Hardel-DW