skip to Main Content

I updated my react version to 18 from version 17, after that this code –> data?.area?.width=['111','220'] is throwing error like this "The left-hand side of an assignment expression must be a variable or a property access.", what will be the solution?

what are the code changes required here?

3

Answers


  1. You haven’t provided enough code information but as per this line (data?.area?.width=['111','220']) I understand that you want to check for condition when the area has width 111 or 220, so for this purpose this will be the condition

    (data?.area?.width===111 || data?.area?.width===220)

    Login or Signup to reply.
  2. That is not a valid syntax to assign the field value with optional chaining (?.).

    You have to check both data and data.area are truthy then assign the value as below:

    data && data.area && data.area.width = ['111','220'];
    

    It interprets same as

    if (data) {
      if (data.area) data.area.width = ['111','220'];
    }
    
    Login or Signup to reply.
  3. The problem is because data?.area?.width=['111','220'] is not valid JS. The react version does not matter.

    data?.area?.width is not valid on the left hand side of an assignment operator.

    Your work around, unfortunately, is:

    //if condition
      //if condition
        data.area.width = ['111','220'];

    A proposal was raised for this and TC39 has taken the decision to not
    include it.

    Here is the discussion link

    There are complications to introducing the feature, some of them being:

    1. If the key (area and/or width) does not exist, do you want to create the keys with default values, or do you want to skip the assignment altogether.
    2. Suppose you have an operation like this:
    a?.b = c()
    

    Then do we execute the method c if a is nullish/undefined, or not.

    There are a few other viewpoints mentioned in the thread. Can go through them to understand the decision better. But you can expect this feature to not be introduced in JS in near future.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search