0

I have object={x:[],y:[],z:[]} got from Api and passed it as prop from <Acomponent/> to child <Bcomponent/> like <Acomponent data={object}/>.

<Bcomponent/> state is {a:[],b:[],c:[]} I want data props from <Acomponent> to be added to state of <Bcomponent/>

(i.e) final state of <Bcomponent/> has to be

{a:[],b:[],c:[],x:[],y:[],z:[]}

How it can be done?

1

3 Answers 3

1

Just use constructor

class Bcomponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                a: [],
                b: [],
                c: [],
                x: props.data.x,
                y: props.data.y,
                z: props.data.z
            }
        }
        ...
    }

or setState in componentWillReceiveProps

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the object spread syntax to merge objects:

class Bcomponent extends React.Component {
    constructor(props) {
        super(props);

        const {data} = props;

        this.state = {
            a: [],
            b: [],
            c: [],
            ...data,
        }
    }

    // ...other functions
}

Comments

0
state = {
 a: [], b: [], c: [], ...this.props.data
};

Demo https://codesandbox.io/s/q30w3q97r9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.