• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

SyntaxError: invalid assignment left-hand side

The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. It may be triggered when a single = sign was used instead of == or === .

SyntaxError or ReferenceError , depending on the syntax.

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of an assignment operator and an equality operator , for example. While a single = sign assigns a value to a variable, the == or === operators compare a value.

Typical invalid assignments

In the if statement, you want to use an equality operator ( === ), and for the string concatenation, the plus ( + ) operator is needed.

Assignments producing ReferenceErrors

Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference , so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed.

Function calls, new calls, super() , and this are all values instead of references. If you want to use them on the left hand side, the assignment target needs to be a property of their produced values instead.

Note: In Firefox and Safari, the first example produces a ReferenceError in non-strict mode, and a SyntaxError in strict mode . Chrome throws a runtime ReferenceError for both strict and non-strict modes.

Using optional chaining as assignment target

Optional chaining is not a valid target of assignment.

Instead, you have to first guard the nullish case.

  • Assignment operators
  • Equality operators

How To Use React useRef Hook

What is the useRef hook? How do you use it? When should you use useRef vs useState ? What caveats should you be aware of when using useRef ?

This hook is often a tricky one to get right but can be very powerful. Read on to learn how to useRef like a pro!

Table of Contents

What is React’s useRef hook?

useRef is one of the standard hooks provided by React. It will return an object that you can use during the whole lifecycle of the component. 

The main use case for the useRef hook is to access a DOM child directly. I’ll show exactly how to do that in another section. 

Although accessing the DOM is the main use case, it doesn’t mean it’s the only one! useRef can also be very useful to hold a mutable value across different renders of your component. 

For example, it’s often quite handy when using external libraries that weren’t made with React in mind.

You can initialize a new ref inside a component with the following code:

You can optionally initialize it with a default value by passing it as an argument to the useRef hook:

Tip: useRef is a hook, and as such can only be used in functional components! To use refs in class components, you have createRef instead. I briefly show how to use createRef further down below. To Learn more about the difference between functional and class-based components in React check out this guide .

How to use React useRef?

Once created, you can get and set the value of the ref by accessing the .current property of the object, like so:

To access a DOM element, you create a ref, assign it to the DOM element you want to target using its ref attribute, then you can use it!

For example, say you want to get the height in pixels of a DOM element. To do this, you have to access the offsetHeight property of the DOM element. But how to get access to the DOM element? With a ref of course!

Tip: In the above example I’ve used useEffect to only call divElement.current.offsetHeight once the component was first rendered. Indeed, at first, the ref is undefined, and it’s only once the component renders and the div is created that it holds its DOM element value!

As you can see refs can be quite tricky to use, and you have to keep a few things in mind.

Caveats of using useRef

Some important things to keep in mind when using useRef are:

A ref changing value doesn’t trigger a re-render

This one is often a tricky one, and trips a lot of developers! It is the opposite behavior of what happens when using useState .

For example, the following code has a bug! Can you spot where it is?

Have you spotted it? If so, good job! The issue is that clicking the button increases the variable counter as expected, but it doesn’t trigger a re-render so we see nothing on the screen!

Tip: to learn how to use click handlers like the handleIncreaseCounter , check out this blog post !

It is useless to add a ref to a dependency array

Adding a ref to a dependency array (for example the one of a useEffect hook) will not trigger the callback! This is also a very common error. 

For example, in the following example, you can click on the button all you want and it won’t print anything to the console!

To fix both of these bugs, you should use useState instead of useRef :

Now it works!

Tip: in the above example, I’ve used the callback form of useState . You can learn more about it in this blog post .

When to avoid using useRef?

Most of the time, if you want to persist state across re-renders of your components you should be using useState instead of useRef. Defaulting to useState, and then only using useRef if you have a specific reason to do so is a good rule to code by!

Check out more info on useState on this blog post!

createRef vs useRef

useRef is the hook to create refs in functional components, but you can also use refs in your class components! The way you do it is by using the createRef function. 

The usage is very similar to useRef:

I hope you now have a good understanding of what refs are and how to use them! 

Here is some good further reading if you want more material on refs and useRef :

  • useRef API reference
  • React’s guide on Refs and the DOM . The guide uses class components but you can translate it pretty easily to functional components and useRef instead!

Related Posts:

  • What is useRef hook in React?
  • How To Use React Checkbox onChange Feature (with…
  • When should you use the useLayoutEffect hook in React?
  • How To Make a Custom Responsivity Hook in React?
  • Brief Introduction To The useEffect Hook In React
  • Build Validation With Yup And React Hook Forms ✔

Avatar photo

👋 Hey, I'm Pierre Ouannes

💬 leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

Upmostly brings you original JavaScript framework tutorials every week.

  • Cheatsheets
  • Write For Us

Copyright © 2024 Upmostly

Home

React useRef() Hook Explained in 3 Steps

In this post you'll learn how to use React.useRef() hook to create persisted mutable values (also known as references or refs), as well as access DOM elements.

Table of Contents

1.1 use case: logging button clicks, 1.2 use case: implementing a stopwatch, 2.1 use case: focusing on an input, 3. updating references restriction, 1. mutable values.

useRef(initialValue) is a built-in React hook that accepts one argument as the initial value and returns a reference (aka ref ). A reference is an object having a special property current .

reference.current accesses the reference value, and reference.current = newValue updates the reference value. Pretty simple.

There are 2 rules to remember about references:

  • The value of the reference is persisted (remains unchanged) between component re-renderings;
  • Updating a reference doesn't trigger a component re-rendering .

Now, let's see how to use useRef() in practice.

The component LogButtonClicks uses a reference to store the number of clicks on a button:

Open the demo.

const countRef = useRef(0) creates a reference countRef initialized with 0 .

When the button is clicked, handle callback is invoked and the reference value is incremented: countRef.current++ . Then the reference value is logged to the console.

Updating the reference value countRef.current++ doesn't trigger component re-rendering. This is demonstrated by the fact that 'I rendered!' is logged to the console just once, at initial rendering, and no re-rendering happens when the reference is updated.

Now a reasonable question: what's the main difference between reference and state?

Reference and state diff

Let's reuse the component LogButtonClicks from the previous section, but this time use useState() hook to count the number of button clicks:

Open the demo and click the button. Each time you click, you will see in the console the message 'I rendered!' — meaning that each time the state is updated, the component re-renders.

So, the 2 main differences between reference and state:

  • Updating a reference doesn't trigger re-rendering, while updating the state makes the component re-render;
  • The reference update is synchronous (the updated reference value is available right away), while the state update is asynchronous (the state variable is updated after re-rendering).

From a higher point of view, references store infrastructure data of side-effects, while the state stores information that is directly rendered on the screen.

You can store inside a reference infrastructure data of side effects: timer ids, socket ids, etc.

The component Stopwatch uses setInterval(callback, time) timer function to increase each second the counter of a stopwatch. The timer id is stored in a reference timerIdRef :

startHandler() function, which is invoked when the Start button is clicked, starts the timer and saves the timer id in the reference timerIdRef.current = setInterval(...) .

To stop the stopwatch user clicks Stop button. The Stop button handler stopHandler accesses the timer id from the reference and stops the timer clearInterval(timerIdRef.current) .

Additionally, if the component unmounts while the stopwatch is active, the cleanup function of useEffect() is going to stop the timer too.

In the stopwatch example, the reference was used to store the infrastructure data — the active timer id.

Side challenge: can you improve the stopwatch by adding a Reset button? Share your solution in a comment below!

2. Accessing DOM elements

Another useful application of the useRef() hook is to access DOM elements directly. This is performed in 3 steps:

  • Define the reference to access the element const elementRef = useRef() ;
  • Assign the reference to ref attribute of the element: <div ref={elementRef}></div> ;
  • After mounting, elementRef.current points to the DOM element.

You would need to access DOM elements, for example, to focus on the input field when the component mounts.

To make it work you'll need to create a reference to the input, assign the reference to ref attribute of the tag, and after mounting call the special method element.focus() on the element.

Here's a possible implementation of the <InputFocus> component:

const inputRef = useRef() creates a reference to hold the input element.

inputRef is then assigned to ref attribute of the input field: <input ref={inputRef} type="text" /> .

React then, after mounting, sets inputRef.current to be the input element. Inside the callback of useEffect() you can set the focus to the input programmatically: inputRef.current.focus() .

Tip: if you want to learn more about useEffect() , I highly recommend checking my post A Simple Explanation of React.useEffect() .

Ref is null on initial rendering

During initial rendering, the reference supposed to hold the DOM element is empty:

During initial rendering React still determines the output of the component, so there's no DOM structure created yet. That's why inputRef.current evaluates to undefined during initial rendering.

useEffect(callback, []) hook invokes the callback right after mounting when the input element has already been created in DOM.

callback function of the useEffect(callback, []) is the right place to access inputRef.current because it is guaranteed that the DOM is constructed.

The function scope of the functional component should either calculate the output or invoke hooks.

That's why updating a reference (as well as updating state) shouldn't be performed inside the immediate scope of the component's function.

The reference must be updated either inside a useEffect() callback or inside handlers (event handlers, timer handlers, etc).

useRef() hook creates references.

Calling const reference = useRef(initialValue) with the initial value returns a special object named reference. The reference object has a property current : you can use this property to read the reference value reference.current , or update reference.current = newValue .

Between the component re-renderings, the value of the reference is persisted.

Updating a reference, contrary to updating state, doesn't trigger component re-rendering.

References can also access DOM elements. Assign the reference to ref attribute of the element you'd like to access: <div ref={reference}>Element</div> — and the element is available at reference.current after the component mounting.

Want to improve your React knowledge further? Follow A Simple Explanation of React.useEffect() .

Challenge: write a custom hook useEffectSkipFirstRender() that works as useEffect() , only that it doesn't invoke the callback after initial rendering (Hint: you need to use useRef() ). Share your solution in a comment below!

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

React useRef Hook By Example: A Complete Guide

  • What is useRef used for?

Directly access DOM nodes

Persist a mutable value across rerenders, the mental model of useref, the "rerendering time loop", component instances, example 1: previous value / state, example 2: stopwatch (clear interval), example 3: press and hold to repeat, anti-patterns, assign to ref.current in render, use ref.current in jsx and expect it to be reactive, quiz & related concepts, ref and useref, useref vs. usestate, useref vs. createref.

useRef is a built-in React Hook. Perhaps you have used it to access DOM nodes (If not, don't worry. It's covered in this post).

But do you know it can do way more? It's a hidden gem 💎. Trust me, it can become a powerful tool in your arsenal.

This is a deep dive into useRef . With an example-driven approach, this article covers:

  • What it is used for
  • Its mental model
  • Simple examples
  • More practical examples

Along the way, we'll build a stopwatch and a like button (yes, exactly the same like button on this blog, feel free to steal the code):

Intended audience

This article assumes that you are familiar with React basics , as well as how to use the useState and useEffect hooks.

.css-1tjpg0v:hover .icon{opacity:1;} What is useRef used for?

The useRef Hook in React can be used to directly access DOM nodes, as well as persist a mutable value across rerenders of a component.

When combined with the ref attribute, we could use useRef to obtain the underlying DOM nodes to perform DOM operations imperatively. In fact, this is really an escape hatch. We should only do this sparsely for things that React doesn't provide a declarative API for, such as focus management. If we use it for everything (in theory we could), we'd lose the benefit of React's declarative programming paradigm .

This is what I'm going to focus on in this article.

Keep reading 👇.

Here's the mental model that works for me:

useRef is like class instance variable for function components.

After a lot of struggle trying to understand useRef , I finally saw this single sentence. And it clicked! If you are hearing the same clicking sound in your mind right now already, feel free to skip to the examples section . Otherwise, if you are not familiar with JavaScript classes or class instance variables, read on. This section is for you.

To understand how useRef works and why we need it, let's get started with a contrived (but useful) example. Can you build a counter without using the useState hook?

Let's give it a try:

This doesn't work, even though the value of count increases on click. Why? React is oblivious to the change of local variables and, therefore, doesn't know when to update the DOM. We'd need to rerender the component, namely request React to call the component function Counter , to let the change reflected on the screen.

You can verify this by uncommenting the line console.log('render') right after let count = 0 . The component isn't rendered when the user clicks the button.

OK. Then what if we force the component to render when count updates?

This doesn't work either. The count displayed on the page stays zero. Even worse, the count value in the console stopped working too. It's always 0 !

BTW, useForceRender above is a custom hook:

Why? This is what I call rerendering time loop .

Every time when the component rerenders, it goes into a time loop. All the local variables in the function will be reset to their original values. That's why count is always 0 .

That's no surprise, right? They are local variables defined in the function. When the function reruns, the variables are supposed to behave like that!

As straighforward as this sounds, sometimes it's easy to forget (I do it all the time). So remember, since a React component is rerendered all the time, all the local variables will go into a time loop, over and over again.

So, we need a solution that survives this "rerendering time loop". We want to preserve the value no matter how many times the component is rendered. If we update count to 42 , at the next render it should still be 42 , not the initial value 0 .

Let's try the first approach: what if we move the variable out of the component function? It will no longer be affected by the rerendering time loop, right?

That's correct! It works! Yay!

But wait a second, what if we want to have two counters?

So our counters are still broken. Did you try it in the preview window? The two counters are tied together. Clicking one button changes the other counter too!

That's because both counters are tied to the same variable count . What we need instead is to have a separate variable for each instance of the counter.

So the requirements are:

  • Persist a value across rerenders
  • Persist the value per component instance, throughout the full lifetime of that instance

Introducing useRef !

But, but we are still using that useForceRender to update the DOM! If we comment out forceRender() , the counter stops working again! (try it)

What's the point of useRef if it relies on useState to work properly? Why don't we just use useState ?

What's the point of useRef if it doesn't trigger a rerender when the value is updated?

In fact, being able to persist a value across rerenders without triggering another rerender is exactly why useRef is created. Sometimes we just don't want the component to rerender when the value is updated.

It's now time to look at a better example.

Let's modify the Counter component. Now we want to display the previous value of the counter whenever the button is clicked. We can do so using a combination of useState , useEffect , and of course useRef .

Look, when saving the previous state in useEffect , we definitely don't want the component to rerender. Otherwise, it'd go into an infinite loop. So, useRef to the rescue!

Now let's look at a more useful example. How about a stopwatch?

We can make the stopwatch tick with a combination of useState , useEffect and setInterval :

But how do we pause the stopwatch?

We can add another state ticking and clear the interval when ticking is false . Let's give it a try:

Did you see the problem? Where should we define that variable interval ?

If we define interval in the outer scope, we'll taste the wrath of the rerendering time loop -- interval will always be undefined .

We don't want to put it in state either, since it's really not something we would want to display on the UI. It's interval stuff.

Again, useRef to the rescue:

Note: due to the way setInterval works in JavaScript, the stopwatch created with the code above is VERY inaccurate. You can check out a more accurate version in CodeSandbox here (but the usage of useRef is still the same).

Let's check out the real thing! Just a reminder, this is what we want to build (remember to click and hold):

We are going to focus on the press-and-hold behavior:

  • When the mouse is down, wait a little bit;
  • If the mouse is still down after a threshold, say 500 milliseconds, start repeatedly increasing the like count at an interval until the mouse is up;

How would we implement this behavior?

In order to detect the press-and-hold gesture, we can use setTimeout . When the mouse is down, kick off the timeout. When the mouse is up, clear the timeout.

How do we set and clear the timeout when the component is rendered and rerendered, i.e. when the state mouseDown changes?

You already know the answer from Example 2, right? useRef !

Next, how do we repeatedly increase the like count? setInterval is what we need. And of course we'll use another ref to keep track of the interval reference across rerenders.

Finally, we can extract all the logic into a custom Hook usePressHoldRepeat :

When using the usePressHoldRepeat hook, remember to use useCallback to prevent excess renders due to the fact the function might be recreated on each render (time loop).

Check out the full source code in this CodeSandbox

Note: The animation in this example is implemented with Framer Motion . If you want to learn how to make the best of it and avoid common pitfalls, check out this full course I made for you!

Remember, updating a ref's value is a side effect. We should put it inside useEffect or event handlers. Don't update current at the top level of a function component.

We could use ref.current in JSX, as you've seen in Example 1 . However, keep in mind that the value displayed might be stale since updating ref.current doesn't trigger a rerender. We need to trigger rerenders in other means, e.g. with useState .

With the understanding of how useRef works, let's look at a few related concepts. I'm going to organize them as quiz questions since I think you'd be able to figure it out with the mental model built after reading this article this far.

Give it a try!

As mentioned, we could use the ref attribute and useRef to obtain the access to underlying DOM nodes, like so:

But, have you wondered how it works?

React receives the ref via the ref attribute of input and mutates it at some point, just as what we did in the examples above:

What is the difference between useRef and useState ? How do they relate to each other?

Both useRef and useState persist a value across rerenders of a component. This means the value doesn’t get reset when the component rerenders, whereas all local variables go into a time loop.

The value tracked by useState is updated via calling the setter function, which triggers a rerender of the component. In comparison, the value tracked by useRef is updated via direct mutation, which does not trigger a rerender.

In React, there's another function called createRef :

What is the difference between useRef and createRef ? I know I didn't cover createRef so far in the article, but can you guess from its name?

Well. It's called create Ref. So every time when it runs, it creates a new ref object.

Hmm... Does that mean useRef does NOT create a new ref object every time when it's called?

Exactly! useRef only creates a ref object for a particular component instance when it's first rendered. In the following rerenders, it'll just returns the existing ref object associated with that component instance. That's why we can trust it to persist a value across rerenders!

In function components, we should always use useRef . creatRef is used in class components to create a ref, where we could keep it in a class instance variable (so that it's not created repeatedly when the component rerenders).

There are two use cases of useRef :

  • Directly access DOM nodes to perform DOM operations imperatively
  • Persist a value across rerenders, throughout the full lifetime of a component instance

The second use is particularly powerful when combined with useEffect , useState and useCallback . In this post, we used it in two real-world scenarios:

  • Preserve previous state
  • Preserve the reference of a timeout or interval so that we can clear them at a later time (in another render round)

Do you have other examples of useRef in your projects? Let me know !

I hope you find this article useful!

One of my 2021 goals is to write more posts that are useful , interactive and entertaining . Want to receive early previews of future posts? Sign up below. No spam, unsubscribe anytime.

You may also like

What is React to do with cutting holes on a cardboard? Surprisingly, they have a lot in common.

How do we work with the HTML input in React? Its behavior might be surprising. Read this post to get a good understanding of Input. And you'll get to do some Kung Fu routines with Panda too.

What is an JSX tag really? It's JavaScript code in disguise. Let's reveal its true face!

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

avatar

Last updated: Feb 28, 2024 Reading time · 4 min

banner

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

The error "The left-hand side of an assignment expression may not be an optional property access" occurs when we try to use optional chaining (?.) to assign a property to an object.

To solve the error, use an if statement that serves as a type guard instead.

Here is an example of how the error occurs.

left hand side of assignment expression may not be optional property

We aren't allowed to use the optional chaining (?.) operator on the left-hand side of an assignment.

# Use an if statement as a type guard to solve the error

To solve the error, use an if statement as a type guard before the assignment.

use if statement as type guard to solve the error

We used the loose not equals operator (!=), to check if the variable is NOT equal to null and undefined .

This works because when compared loosely, null is equal to undefined .

The if block is only run if employee doesn't store an undefined or a null value.

This is similar to what the optional chaining (?.) operator does.

# Using the non-null assertion operator to solve the error

You might also see examples online that use the non-null assertion operator to solve the error.

The exclamation mark is the non-null assertion operator in TypeScript.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined .

Here is an example of using this approach to set a property on an object.

using non null assertion to solve the error

In most cases, you should use a simple if statement that serves as a type guard as we did in the previous code sample.

# Avoiding the error with a type assertion

You can also use a type assertion to avoid getting the error. However, this isn't recommended.

avoiding the error with type assertion

The (employee as Employee) syntax is called a type assertion.

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the employee variable will have a type of Employee and not to worry about it.

This could go wrong if the variable is null or undefined as accessing a property on a null or an undefined value would cause a runtime error.

# Using the logical AND (&&) operator to get around the error

You can also use the logical AND (&&) operator to avoid getting the error.

using logical and operator to get around the error

The logical AND (&&) operator checks if the value to the left is truthy before evaluating the statement in the parentheses.

If the employee variable stores a falsy value (e.g. null or undefined ), the code to the right of the logical AND (&&) operator won't run at all.

The falsy values in JavaScript are: false , undefined , null , 0 , "" (empty string), NaN (not a number).

All other values are truthy.

However, this approach can only be used to assign a single property at a time if the value is not equal to null and undefined .

# The optional chaining operator should only be used when accessing properties

The optional chaining (?.) operator short-circuits if the reference is equal to null or undefined .

The optional chaining (?.) operator will simply return undefined in the example because employee has a value of undefined .

The purpose of the optional chaining (?.) operator is accessing deeply nested properties without erroring out if a value in the chain is equal to null or undefined .

However, the optional chaining operator cannot be used on the left-hand side of an assignment expression.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Check the Type of a Variable in TypeScript
  • Exclamation Mark (non-null assertion) operator in TypeScript
  • The ?. operator (optional chaining) in TypeScript
  • Declare and Type a nested Object in TypeScript
  • How to Add a property to an Object in TypeScript
  • Check if a Property exists in an Object in TypeScript
  • The left-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

DEV Community

DEV Community

Wojciech Matuszewski

Posted on Jun 12, 2021

Mutable and immutable useRef semantics with React & TypeScript

In this post, you will learn how different ways declaring a ref with useRef hook influence the immutability of the current ref property. We will be looking at how to make the current property immutable, mutable, and know without much effort if the ref is one or the other.

All the behavior I'm going to talk about is only relevant in the context of TypeScript. The mutability / immutability is enforced at type level, not runtime level .

Immutable current property

The immutable semantics of the useRef hooks are usually used with DOM elements. A common use-case might be to get the ref of an element and focus that element whenever a button is clicked.

Here is how I would write that.

Notice the type and the value I’ve initialized the useRef with. The semantics I’ve used signal that I’m relying on React to manage the ref for me. In our case, this means that I cannot mutate the inputRef.current . If I ever tried to do that, TypeScript would complain.

After writing similar code for a while, I’ve created a rule of thumb I follow to understand if the ref that I’m looking is immutable.

If the useRef is initialized with null and the initial value does not belong to the provided type, the current property is immutable.

In our case, the null initial value does not belong to the type HTMLInputElement so the current property cannot be mutated.

Mutable current property

To have the current property of the ref be mutable, we need to change how we are declaring ref itself.

Suppose we are writing a component that deals with timers. The useRef hook is an ideal candidate to hold a reference to a timer. With the timer reference at hand, we can make sure that we clear the timer when the component unmounts.

Here is an, albeit a bit contrived, example.

Since in the beginning, I have no way to know what the reference to the later declared setTimeout might be, I've initialized the useRef with null . Apart from the types, the declaration of the ref might seem eerily similar to the one in the Immutable current property section. However, since the initially provided value (in our case null ) wholly belongs to the type I've declared the useRef with ( number | null ), the current property is allowed to be mutable.

Similarly to the immutable current property case, here is my rule of thumb.

If the useRef is initialized with a value that belongs to the provided type, the current property of the ref is mutable.

In our case, the null initial value belongs to the type number | null so the current property can be mutated. As an alternative, I could have declared the timerRef variable the following way

Why is the current allowed to be mutated in this case? Because the timerRef is implicitly initialized with the undefined value. The undefined value belongs to the type I've declared the timerRef - the React.useRef typings are overloaded depending on the type of the initial value.

When I started working with React & TypeScript, I found the difference between mutable and immutable refs quite confusing. I hope that this article was helpful and cleared some of the questions you might have had on the subject matter.

You can find me on twitter - @wm_matuszewski .

Thank you for your time.

Top comments (12)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

maciekgrzybek profile image

  • Location Białystok
  • Work Senior Frontend Developer @ Ramp.Network
  • Joined Feb 20, 2019

Nice 😊II like reading about these kinds of nuances 👌

fchaplin profile image

  • Location Montpellier, France
  • Work Senior Fullstack Developer
  • Joined Jan 22, 2021

Thank you ! A question : your constants are declared as any. Shouldn't we type every declaration in Typescript ?

wojciechmatuszewski profile image

  • Work Serverless Engineer at StediInc
  • Joined May 3, 2019

Hey, thank you for reaching out.

In TypeScript, you can leverage type inference . So, while I could explicitly annotate every variable with the corresponding type, I defer that work until necessary and rely on the notion of type inference.

You can read more about type inference here: typescriptlang.org/docs/handbook/t...

Yep, but it may be a better practice to explicitly type your constants while declaring them, especially when inferred type is not basic. You may gain time on weird issues later. And your code may be clearer when debugging 🙂.

nicholasboll profile image

  • Joined Mar 5, 2018

I think explicitly typing everything makes it harder to read and now you have to understand the nuances of when you should or should not explicitly type.

Not only is the second one harder to read and parse, it actually widened our type.

This is a really simple assignation example and I agree with you on this (except for a little typo) . But for function returns, and libs specific types, making a rule of typing explicitly everything WILL help.

By explicitly typing, you give explicitly the mutability information to other developpers (or to you in a month or two). So you improve readability.

And if you try

Here, typescript tell you instantly you're making a mistake: "No, it's not mutable!".

I know there are many sources that says you can use implicit types, but if you use them too much, you may lose some typescript gifts.

I'd probably argue there should be a useMutableRef and useRef rather than complicated types to communicate intent. I often have these small functions that map to normal functions to more clearly communicate intent:

It is even possible to create nice utility functions that make element refs easier to work with:

Notice the theme where the Typescript types start to disappear for normal usage? This means you can still get the benefits of Typescript without explicitly using Typescript. Even JavaScript users of your code can benefit. This technique works better for libraries, especially if you have JavaScript users of your library. You can use JSDoc to explicitly type JS code, but that is a pain for non-primitive types.

I say there doesn't need to be a tradeoff between Typescript gifts and expressing intent. If your team only uses Typescript and understands all the types in use, maybe you don't need to spend any extra time communicating intent through functions. But it is very useful for JavaScript users in addition to Typescript users who don't spend time finding out all the nuances of Typescript type differences like useRef . You have to learn something extra either way (type differences or which function to use), but why not communicate intent explicitly through names vs types?

Because in this example case Typescript may :

  • throw exceptions at compile time
  • and give intent to the reader
  • without adding more code.

doctorderek profile image

  • Joined Nov 24, 2020

I actually never type anything in TypeScript unless I have to, and I consider explicit types to be an antipattern.

In my opinion, it's easy to check VSCode's Intellisense to make sure that the right type was inferred.

In React, for example, I've never had to actually use the FC type or explicitly return JSX.Element; if I write a function component, then TypeScript catches it 100% of the time.

There are definitely certain cases where I type function returns, such as if I'm using a "pseudo enum" (union type of strings) and want to coerce the function return down from string to either "thingOne" | "thingTwo" -- so I do see your point.

Overall, I don't think it's useful for productivity or type safety to explicitly type things when the implicit type was correct, so I try to avoid it.

arian94 profile image

  • Joined May 5, 2024

I did mutate an object that was created using useRef and initialized it with null like this:

Then, mutate it like below:

The only thing happening here is that TypeScript will throw error since we are mutating a 'read-only' property but if you ignore this error, it does mutate it anyway.

kazamov profile image

  • Joined Jun 15, 2019

Thanks for the explanation!

essentialrandom profile image

  • Work Full Stack Developer
  • Joined Jan 27, 2019

Thank you!! This kept tripping me up every time.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

parmcoder profile image

Microservices are Technical Debt

Possawat Sanorkam - Sep 22

adrianbailador profile image

How to Integrate RabbitMQ with .NET: Practical Guide, Routing Patterns, and Error Handling

Adrián Bailador - Sep 9

imevanc profile image

🚀 Casenator Just Got Even Better: New Case Styles and Dev-Friendly Updates!

Evan Charalampidis - Sep 8

vinod_kumar_7b58f9beecf58 profile image

Want to switch node

Vinod Kumar - Sep 9

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

How to fix SyntaxError: invalid assignment left-hand side

Let me show you an example that causes this error and how I fix it.

How to reproduce this error

How to fix this error, other causes for this error.

You can also see this error when you use optional chaining as the assignment target.

Take your skills to the next level ⚡️

useRef is a React Hook that lets you reference a value that’s not needed for rendering.

useRef(initialValue)

Referencing a value with a ref, manipulating the dom with a ref, avoiding recreating the ref contents, i can’t get a ref to a custom component.

Call useRef at the top level of your component to declare a ref.

See more examples below.

  • initialValue : The value you want the ref object’s current property to be initially. It can be a value of any type. This argument is ignored after the initial render.

useRef returns an object with a single property:

  • current : Initially, it’s set to the initialValue you have passed. You can later set it to something else. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property.

On the next renders, useRef will return the same object.

  • You can mutate the ref.current property. Unlike state, it is mutable. However, if it holds an object that is used for rendering (for example, a piece of your state), then you shouldn’t mutate that object.
  • When you change the ref.current property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object.
  • Do not write or read ref.current during rendering, except for initialization. This makes your component’s behavior unpredictable.
  • In Strict Mode, React will call your component function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. Each ref object will be created twice, but one of the versions will be discarded. If your component function is pure (as it should be), this should not affect the behavior.

Call useRef at the top level of your component to declare one or more refs.

useRef returns a ref object with a single current property initially set to the initial value you provided.

On the next renders, useRef will return the same object. You can change its current property to store information and read it later. This might remind you of state , but there is an important difference.

Changing a ref does not trigger a re-render. This means refs are perfect for storing information that doesn’t affect the visual output of your component. For example, if you need to store an interval ID and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its current property :

Later, you can read that interval ID from the ref so that you can call clear that interval :

By using a ref, you ensure that:

  • You can store information between re-renders (unlike regular variables, which reset on every render).
  • Changing it does not trigger a re-render (unlike state variables, which trigger a re-render).
  • The information is local to each copy of your component (unlike the variables outside, which are shared).

Changing a ref does not trigger a re-render, so refs are not appropriate for storing information you want to display on the screen. Use state for that instead. Read more about choosing between useRef and useState .

Examples of referencing a value with useRef

Example 1 of 2 : click counter.

This component uses a ref to keep track of how many times the button was clicked. Note that it’s okay to use a ref instead of state here because the click count is only read and written in an event handler.

If you show {ref.current} in the JSX, the number won’t update on click. This is because setting ref.current does not trigger a re-render. Information that’s used for rendering should be state instead.

Do not write or read ref.current during rendering.

React expects that the body of your component behaves like a pure function :

  • If the inputs ( props , state , and context ) are the same, it should return exactly the same JSX.
  • Calling it in a different order or with different arguments should not affect the results of other calls.

Reading or writing a ref during rendering breaks these expectations.

You can read or write refs from event handlers or effects instead .

If you have to read or write something during rendering, use state instead.

When you break these rules, your component might still work, but most of the newer features we’re adding to React will rely on these expectations. Read more about keeping your components pure.

It’s particularly common to use a ref to manipulate the DOM. React has built-in support for this.

First, declare a ref object with an initial value of null :

Then pass your ref object as the ref attribute to the JSX of the DOM node you want to manipulate:

After React creates the DOM node and puts it on the screen, React will set the current property of your ref object to that DOM node. Now you can access the <input> ’s DOM node and call methods like focus() :

React will set the current property back to null when the node is removed from the screen.

Read more about manipulating the DOM with refs.

Examples of manipulating the DOM with useRef

Example 1 of 4 : focusing a text input.

In this example, clicking the button will focus the input:

React saves the initial ref value once and ignores it on the next renders.

Although the result of new VideoPlayer() is only used for the initial render, you’re still calling this function on every render. This can be wasteful if it’s creating expensive objects.

To solve it, you may initialize the ref like this instead:

Normally, writing or reading ref.current during render is not allowed. However, it’s fine in this case because the result is always the same, and the condition only executes during initialization so it’s fully predictable.

How to avoid null checks when initializing useRef later

If you use a type checker and don’t want to always check for null , you can try a pattern like this instead:

Here, the playerRef itself is nullable. However, you should be able to convince your type checker that there is no case in which getPlayer() returns null . Then use getPlayer() in your event handlers.

Troubleshooting

If you try to pass a ref to your own component like this:

You might get an error in the console:

By default, your own components don’t expose refs to the DOM nodes inside them.

To fix this, find the component that you want to get a ref to:

And then wrap it in forwardRef like this:

Then the parent component can get a ref to it.

Read more about accessing another component’s DOM nodes.

Optional Chaining for Assignments Lands in Stage 1

Matt Pocock

In TypeScript, if you try to assign to a property of a possibly undefined object, you'll get an error:

'X' is possibly undefined.

You might think that you can use the optional chaining syntax to fix this:

But you end up with an error:

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

This is because optional chaining is only for reading properties (or deleting properties), not for assigning to them.

But today, the optional chaining for assignments proposal has landed in Stage 1 of TC39.

If this proposal gets adopted into JavaScript, the code below will no longer error.

Share this article with your friends

react useref invalid left hand side in assignment expression

This Crazy Syntax Lets You Get An Array Element's Type self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn how to extract the type of an array element in TypeScript using the powerful Array[number] trick.

Matt Pocock

How To Create An NPM Package self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn how to publish a package to npm with a complete setup including, TypeScript, Prettier, Vitest, GitHub Actions, and versioning with Changesets.

react useref invalid left hand side in assignment expression

Why I Don't Like Enums self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Enums in TypeScript can be confusing, with differences between numeric and string enums causing unexpected behaviors.

react useref invalid left hand side in assignment expression

Is TypeScript Just A Linter? self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Is TypeScript just a linter? No, but yes.

react useref invalid left hand side in assignment expression

Announcing: A Free Book, A New Course, A Huge Price Cut... self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

It's a massive ship day. We're launching a free TypeScript book, new course, giveaway, price cut, and sale.

react useref invalid left hand side in assignment expression

Sometimes, Object Property Order Matters self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn why the order you specify object properties in TypeScript matters and how it can affect type inference in your functions.

This forum is now read-only. Please use our new forums! Go to forums

react useref invalid left hand side in assignment expression

Syntax Error: "Invalid Left-hand Side in assignment."

I am unsure what else is necessary in my code. My syntax is as follows:

var isEven = function(number) {

if (number % 2 === 0){ return true; }

else if (isNan(number) = true) { return “This is not a number!”; }

else { return false; }

isEven (“r”)

First, I would like to know what this error code means. Secondly, I would like further insight into how one would use isNaN in this code.

Answer 5605035486f55253a300022e

if you want to compare two values you need to use == or ===, = just tries to assign the value on the left to the variable on the right. And here is the problem as you have a value on the left and not a variable which is why you get that:

To get rid of it just fix the comparison:

or get rid of the == true or === true and just use:

as a comparision with true is always what it was before e.g.

if isNan(number) is false:

and if it is true:

react useref invalid left hand side in assignment expression

Answer 560a184286f552cb7c000371

if(number%2===0) { return true; } else if (isNaN(number)===true) { return “Your input type is notcorrect”; }

else { return false; } };isEven(“hi”);

react useref invalid left hand side in assignment expression

worked for me

Popular free courses

Learn javascript.

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript ReferenceError – Invalid assignment left-hand side

This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment.

Error Type:

Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.

Basic Example of ReferenceError – Invalid assignment left-hand side, run the code and check the console

Example 1: In this example, “=” operator is misused as “==”, So the error occurred.

Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.

Output: 

Please Login to comment...

Similar reads.

  • Web Technologies
  • JavaScript-Errors
  • How to Underline in Discord
  • How to Block Someone on Discord
  • How to Report Someone on Discord
  • How to add Bots to Discord Servers
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Invalid left-hand side in assignment expression

New person here working on a toy problem building a function that converts a string to camelcase anywhere there is a dash or an underscore. I have almost everything worked out except the second to last line of the function where I am trying to change the characters at each index (from my index array) to uppercase before I return the string. The error I am getting is bad assignment from the left side, but I'm not sure why. I've console logged both sides of the assignment and they seem to be doing what I want, but the assignment itself isn't working. Thank you for any help!

Here is the code:

function toCamelCase(str){ var stringArray = str.split(''); var indexArray = []; stringArray.forEach(character => { if (character === '-' || character === '_') { var index = str.indexOf(character); str = str.slice(0, index) + str.slice(index+1) indexArray.push(index); } return character; }) indexArray.forEach(index => {stringArray.splice(index, 1)}); string = stringArray.join(''); indexArray.forEach(index => {string.charAt(index) = string.charAt(index).toUpperCase()}); return string; }

  • variable-assignment

mateotherock's user avatar

  • Possible duplicate of Why does chartAt() cause an "Invalid left-hand side in assignment" error in JavaScript? –  Guilherme Lemmi Commented Apr 27, 2018 at 22:50

4 Answers 4

The problem is with using string.charAt() on the left hand side. That is not possible as you're trying to assign something to the result of a function, all in the same call. Store the value of string.charAt() in an intermediary variable and it should work. Check the code below for a working example, using a slightly different approach:

Guilherme Lemmi's user avatar

Ah thank you both for pointing me in the right direction. Instead of joining it back to a string I took advantage of it being an array already and just looped through that first.

This code worked...

function toCamelCase(str){ var stringArray = str.split(''); var indexArray = []; stringArray.forEach(character => { if (character === '-' || character === '_') { var index = str.indexOf(character); str = str.slice(0, index) + str.slice(index+1) indexArray.push(index); } return character; }) indexArray.forEach(index => {stringArray.splice(index, 1)}); indexArray.forEach(index => {stringArray[index] = stringArray[index].toUpperCase()}); var string = stringArray.join(''); return string; }

For taking an approach by iterating the characters, you could use a flag for the following upper case letter.

function toCamelCase(str) { var upper = false; return str .split('') .map(c => { if (c === '-' || c === '_') { upper = true; return ''; } if (upper) { upper = false; return c.toUpperCase(); } return c; }) .join(''); } console.log(toCamelCase('foo----bar_baz'));

qqq's user avatar

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where the Parsing error: Invalid left-hand side in assignment expression occurred. More context here.

Lukasz Dynowski's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript variable-assignment or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Should low-scoring meta questions no longer be hidden on the Meta.SO home...
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Day Convolution of Sheaves
  • If I was ever deported, would it only be to my country of citizenship? Or can I arrange something else?
  • Solving a "One Away.." connections group with nine guesses
  • Print 4 billion if statements
  • How do Cultivator Colossus and bounce lands interact?
  • Could you compress chocolate such that it has the same density and shape as a real copper coin?
  • Does the old type of rubber hose Dunlop valves haves any pros compared to the modern ones without rubber?
  • Do all languages distinguish between persons and non-persons?
  • How can I grep to include the surrounding lines?
  • 2000s creepy independant film with a voice-over of a radio host giving bad self-help advice
  • cURL in bash script reads $HOME as /root/
  • Musicians wearing Headphones
  • Is there any reason _not_ to add a flyback diode?
  • How is the universe able to run physics so smoothly?
  • Does AI use lots of water?
  • What causes, and how to avoid, finger numbness?
  • Can a floppy disk be wiped securely using the Windows format command with the passes-parameter?
  • In the absence of an agreement addressing the issue, is there any law giving a university copyright in an undergraduate student's class paper?
  • Need help with a system of 2 very verbose equations
  • Are there individual protons and neutrons in a nucleus?
  • Lovecraftian (but not written by Lovecraft himself) horror story featuring a body of water that glowed blue at night due to the creatures in it
  • The meaning(s) of 'She couldn't buy a car yesterday.'
  • Is there any language which distinguishes between “un” as in “not” and “un” as in “inverse”?
  • Dark setting action fantasy anime; protagonist has white hair, wears black, slim clothes, and fights with his hand

react useref invalid left hand side in assignment expression

IMAGES

  1. javascript

    react useref invalid left hand side in assignment expression

  2. 报错-Invalid left-hand side in assignment_invalid left-hand side in

    react useref invalid left hand side in assignment expression

  3. Invalid Left Hand Side In Assignment

    react useref invalid left hand side in assignment expression

  4. Invalid Left Hand Side in Assignment: Discover the Fix

    react useref invalid left hand side in assignment expression

  5. Page error: Invalid Left-Hand Side in Assignment

    react useref invalid left hand side in assignment expression

  6. Invalid left-hand side in assignment页面报错问题解决方法-CSDN博客

    react useref invalid left hand side in assignment expression

VIDEO

  1. useRef 훅 누구보다 쉽게 설명해드림

  2. Don't use forwardRef in React

  3. React's useRef Hook: How is it different to useState?

  4. #4: React Hooks

  5. Level Up Your React Skills with the useRef Hook

  6. FNF Invalid Data S-side charts WEEK 2 full playthrough

COMMENTS

  1. javascript

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  2. SyntaxError: invalid assignment left-hand side

    Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference, so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed. Function calls, new calls, super(), and this ...

  3. Mastering Refs in React: Practical Guide with useRef and forwardRef

    Here, useRef is used to create an object meaningRefs where each property is a ref corresponding to a particular meaning.useRef returns a mutable ref object whose .current property is initialized to the passed argument (null in this case). The object persists for the full lifetime of the component. We create a dictionary of meaning references using the useRef hook.

  4. How To Use React useRef Hook (with Examples)

    You can initialize a new ref inside a component with the following code: // create a ref const yourRef = useRef(); You can optionally initialize it with a default value by passing it as an argument to the useRef hook: // create a ref const yourRef = useRef('hello world'); Tip: useRef is a hook, and as such can only be used in functional components!

  5. React useRef() Hook Explained in 3 Steps

    reference.current accesses the reference value, and reference.current = newValue updates the reference value. Pretty simple. There are 2 rules to remember about references: The value of the reference is persisted (remains unchanged) between component re-renderings;; Updating a reference doesn't trigger a component re-rendering.; Now, let's see how to use useRef() in practice.

  6. Mastering React's useRef Hook: A Deep Dive

    React's useRef hook is a powerful and versatile tool that allows you to interact with the DOM, manage state, and optimize performance without causing unnecessary re-renders. In this comprehensive guide, we'll take a deep dive into how useRef works under the hood, why it doesn't trigger re-renders, and how you can harness its full potential.

  7. React useRef Hook By Example: A Complete Guide

    The useRef Hook in React can be used to directly access DOM nodes, as well as persist a mutable value across rerenders of a component. Directly access DOM nodes When combined with the ref attribute, we could use useRef to obtain the underlying DOM nodes to perform DOM operations imperatively.

  8. The left-hand side of assignment expression may not be an optional

    However, the optional chaining operator cannot be used on the left-hand side of an assignment expression. # Additional Resources. You can learn more about the related topics by checking out the following tutorials: How to Check the Type of a Variable in TypeScript; Exclamation Mark (non-null assertion) operator in TypeScript

  9. React v18: useRef

    Part 1: Taming React's necessary evil — useRef. The concept of values and references is not new to any programmer. Values are what the name suggests, simple snapshots of data at a point in time. To jog your memory for the latter, references are pointers to some data which may change over time, but the reference itself remains the same.

  10. Mutable and immutable useRef semantics with React & TypeScript

    After writing similar code for a while, I've created a rule of thumb I follow to understand if the ref that I'm looking is immutable. If the useRef is initialized with null and the initial value does not belong to the provided type, the current property is immutable.. In our case, the null initial value does not belong to the type HTMLInputElement so the current property cannot be mutated.

  11. Referencing Values with Refs

    Adding a ref to your component. You can add a ref to your component by importing the useRef Hook from React: Inside your component, call the useRef Hook and pass the initial value that you want to reference as the only argument. For example, here is a ref to the value 0: current: 0 // The value you passed to useRef.

  12. How to fix SyntaxError: invalid assignment left-hand side

    SyntaxError: invalid assignment left-hand side or SyntaxError: Invalid left-hand side in assignment Both errors are the same, and they occured when you use the single equal = sign instead of double == or triple === equals when writing a conditional statement with multiple conditions.

  13. useRef

    useRef returns a ref object with a single current property initially set to the initial value you provided.. On the next renders, useRef will return the same object. You can change its current property to store information and read it later. This might remind you of state, but there is an important difference.. Changing a ref does not trigger a re-render. This means refs are perfect for ...

  14. Optional Chaining for Assignments Lands in Stage 1

    The left-hand side of an assignment expression may not be an optional property access. This is because optional chaining is only for reading properties (or deleting properties), not for assigning to them. But today, the optional chaining for assignments proposal has landed in Stage 1 of TC39. If this proposal gets adopted into JavaScript, the ...

  15. Syntax Error: "Invalid Left-hand Side in assignment."

    And here is the problem as you have a value on the left and not a variable which is why you get that: Syntax Error: "Invalid Left-hand Side in assignment." To get rid of it just fix the comparison: isNan(number) == true. or. isNan(number) === true. or get rid of the == true or === true and just use: isNan(number)

  16. How to fix SyntaxError

    When you attempt to assign a value to a literal like a number, string or boolean it will result in SyntaxError: Invalid Assignment Left-Hand Side. Example: 5 = x; Output. SyntaxError: invalid assignment left-hand side Resolution of error

  17. javascript

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  18. JavaScript ReferenceError

    This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single "=" sign instead of "==" or "===" is an Invalid assignment. Message:

  19. Invalid left-hand side in assignment expression

    2. The problem is with using string.charAt () on the left hand side. That is not possible as you're trying to assign something to the result of a function, all in the same call. Store the value of string.charAt () in an intermediary variable and it should work.