0

I am working on a reactJS application using TypeScript. I have created a class:

export class A{
  showLegend: boolean = true;
  showToolTip:boolean = true;
  showDataLabel:boolean = false;
  legendText: string = "Smith-Chart";
  showAnimation:boolean = false;
  legendPosition:string = "Bottom";
  showMarker:boolean = true;
  showMarkerLines:boolean = true;
  linesColor:string = "";
  markerColor:string = "";
  markerBorderColor:string = "";
  markerBorderWidth:number = 2;
}

My props has two objects of this class:

let localCopy : A[]
constructor(props: any){
  super(props);
  localCopy = this.props.slice;
}

This does copy the data into the localCopy array, but when i update the localCopy, the actual props are also updated.

How can i copy the props my value and not by reference ?

Waleed Naveed
  • 2,293
  • 2
  • 29
  • 57
  • Props are Read-Only refers to https://reactjs.org/docs/components-and-props.html if you mean copy the props you can try `...this.props` – atadnmz Feb 28 '20 at 13:36
  • i want to copy the props by value, so if i made changes to copied array, those changes should not be shown in props – Waleed Naveed Feb 28 '20 at 13:38
  • There is no way to change props as I said it is read-only. It cannot be updated. Try to assign a value to props. error says `Uncaught TypeError: Cannot assign to read only property 'data' of object '#'` – atadnmz Feb 28 '20 at 13:55
  • I am not updating props, i just want to save props in a new variable @atadnmz – Waleed Naveed Feb 28 '20 at 13:56

1 Answers1

0

you can copy immutably in this way

localCopy = {...this.props};

equivalent in ES5 was

localCopy = Object.assign({}, this.props);
FarukT
  • 1,560
  • 11
  • 25
  • If you want to read more about the advantages/disadvantages, there's already a question on SO about this here: https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign – Thomas L Feb 28 '20 at 13:36