Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React : cannot add property 'X', object is not extensible

I am receiving props in my component. I want to add a property 'LegendPosition' with the props in this component. I am unable to do that. Please help me with this. I have tried this code yet but no success:

var tempProps     = this.props;
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);

console.log(tempProps);
like image 800
Ankit Kaushal Avatar asked Apr 08 '19 06:04

Ankit Kaushal


People also ask

How do you fix an object is not extensible?

To fix this error, you will either need to remove the call to Object. preventExtensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.

How many elements do react components return?

In react component, we can return only one element.


1 Answers

You can't modify this.props. Here tempProps is reference of this.props so it does not work. You should create a copy of the props using JSON.parse() and JSON.stringify()

var tempProps = JSON.parse(JSON.stringify(this.props));
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);

console.log(tempProps);

For a better and efficient way to deep clone object see What is the most efficient way to deep clone an object in JavaScript?

like image 82
Maheer Ali Avatar answered Sep 18 '22 08:09

Maheer Ali