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

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?


I want to send the updated props to a child component, If it is possible without copying or cloning to a new object, Please help me how can I achieve this.

Solution is as simple as:

<ChildComponent {...this.props} legendPosition="right" />

Of course legendPosition will be available in ChildComponent by this.props.legendPosition.

Of course earlier this.props can contain already legendPosition property/value which will be overwritten by defined later - order matters.

Of course there can be many spread operators - for multiple properties, logic blocks ... whatever:

const additonalProps = {
  legendPosition: 'right',
  sthElse: true
}
return (
  <ChildComponent {...this.props} {...additonalProps} />
)

props is not mutable, you cant "add" anything to them. if you want to "copy" them then you need to do

const tempProps = {...this.props};

And the only reason i can see you needing to add more props is to pass it down to a child, but you can do that without adding it to the props object.

EDIT: add props with extra prop

<Component {...this.props} legendPosition="right" />

below in tempProps object spread operator copy your this.props object and after spread operator we can add new object property or we can update existing object property.

var tempProps = {
  ...this.props,
  tempProps.legendPosition = 'right' //property you want to add in props object
};