Vasudev
Vasudev

Reputation: 1007

How to modify a prop and not reflect the change in parent

I want to change some inner property of a prop. Props claim to be immutable, but when I change the value, the parent's state value is getting changed.I read that props are immutable. But changing the value is reflecting in parent.

class ParentComp extends React.Component {
    constructor(props) {
        super(props);
        let property = {someProperty:'ABCD'};
        this.state={
            myState: property
        }
    }

    render() {
        return(
            <div>
                Parent:{JSON.stringify(this.state.myState)}
                <ChildComp pState={this.state.myState} />
            </div>
        );
    }
}

class ChildComp extends React.Component {
    render() {
        this.props.pState.someProperty = '1234';
        return(
            <div>
                Child:{JSON.stringify(this.props.pState)}
            </div>
        );
    }
}

At the end, I see both the values are changed to 1234. In online fiddles, it is working as expected(ie., parent value is not changed.). But in my project, the parent is being changed.

How do I achieve this usecase, wherein I want to change some properties in props, and not reflect in the parent's state?

Upvotes: 0

Views: 77

Answers (2)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

I read that props are immutable

That's not true - you only should treat them as they were immutable. In other words, they are just regular javascript Objects and you should not mutate them.

Upvotes: 1

Hitesh Chaudhari
Hitesh Chaudhari

Reputation: 715

If you want to change the value of the props, you should dump the props in the state first then do the mutation on that state.

Mutating props is not best practice. So your ChildComp should be like:

class ChildComp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pState: props.pState,
        }
    }

    componentDidMount() {
        const { pState } = this.state.
        pState.someProperty = '1234';
        this.setState({
            pState,
        });
    }

    render() {
        return(
            <div>    
                Child:{JSON.stringify(this.state.pState)}
            </div>
        );
    }
}

Upvotes: 0

Related Questions