REACT- TypeError: Cannot assign to read only property 'color' of object

Viewed 295

REACTJS learner here. I am trying to toggle the text via useReducer but it doesn't seems to work and I have no idea why. I keep getting the warning message of cannot assign to read only property 'color' of object. However, when I remove the style tag style={listt.list[0].style in <h2> tag. The text 'color=purple' changed to 'color=red' and the console log shows the mutated list well. So I have really no idea what is the problem here. Any help would be greatly appreciated! Here is the link to codesandbox. https://codesandbox.io/s/state-prob-cd21c?file=/src/Toggle.js

import React, { useReducer } from "react";

function Texting() {
  const state = {
    list: [{ name: "I am awesome", style: { color: "purple" } }],
  };

  function reducer(listt, action) {
    switch (action) {
      case "toggle":
        const clone = [...listt.list]; //clone is new copy
        clone[0].style.color = "red";
        console.log(clone);
        return { ...listt, list: clone };
    }
  }
  const [listt, dispatch] = useReducer(reducer, state);
  console.log("new list is " + JSON.stringify(listt.list[0].style));
  return (
    <div>
      Color = {listt.list.map((x) => x.style.color)}
      <button onClick={() => dispatch("toggle")}>toggle!</button>
      <h2 style={listt.list[0].style}>
        Why Error : TypeError: Cannot assign to read only property 'color' of
        object
      </h2>
    </div>
  );
}

export default Texting;
1 Answers

You must provide new style object to clone. Try following:

clone[0].style = {color : "red"}; 

Since your style object contains only color property, you can use above code. If in case it contains multiple properties use following

clone[0].style = {...clone[0].style, color : "red"};

Note: These solutions are specific to the code that you have provided. But in live project we don't specify hard coded indexes values

Related