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