React – TypeScript project – useRef Hook – The left-hand side of an assignment expression may not be an optional property access

React

How to fix “The left-hand side of an assignment expression may not be an optional property access”

React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.

How to reproduce it

import { ReactElement, useRef } from "react";

export default function UseRefDemo(): ReactElement {

    let node = useRef<HTMLSpanElement>(null);

    function action() {
        node.current?.innerHTML = "Changed";
    }
    return (
        <>
            <button onClick={action}>Demo</button>
            <span ref={node}></span>
        </>
    );
}

Error
The left-hand side of an assignment expression may not be an optional property access.

Solution #1

Use the non-null assertion operator (!) instead of an automatically generated ? character.

import { ReactElement, useRef } from "react";

export default function UseRefDemo(): ReactElement {

    let node = useRef<HTMLSpanElement>(null);

    function action() {
       node.current!.innerHTML = "Changed";
    }
    return (
        <>
            <button onClick={action}>Demo</button>
            <span ref={node}></span>
        </>
    );
}

Solution #2

Use a temporary variable.

import { ReactElement, useRef } from "react";

export default function UseRefDemo(): ReactElement {

    let node = useRef<HTMLSpanElement>(null);

    function action() {
        let spanElement: any = node.current;
        spanElement.innerHTML = "Changed";
    }
    return (
        <>
            <button onClick={action}>Demo</button>
            <span ref={node}></span>
        </>
    );
}

Solution #3

Use type guard.

import { ReactElement, useRef } from "react";

export default function UseRefDemo(): ReactElement {

    let node = useRef<HTMLSpanElement>(null);

    function action() {

        const nodeId: string | undefined = node.current?.id;

        if (nodeId) {
            const spanElement = document.getElementById(nodeId);
            spanElement!.innerHTML = "Changed";
        }
    }
    return (
        <>
            <button onClick={action}>Demo</button>
            <span ref={node}></span>
        </>
    );
}
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *