简体   繁体   中英

How to pass updated array object to parent component from child component in reactJs

I am add, editing, updating and removing array elements in my component that is working perfectly.

Problem is that I am not able to do the same process for parent component because I need to pass that array data to parent component.

An array got item in child component ( send that item to parent component array too )

A update ( update actual one item but similar object in parent component array too )

Same goes for delete too.

I am unable to update the parent array while doing all this in child component.

I want to have updated array in my parent component. Below is the code.

Child Component:

// child component saving element in an array
    saveLeadPlanDialog = () => {

        const {updateMode, lead_id, year, probability, plan2, plan3, fee, addcosts} = this.state;

        // here i am setting that data in child component
        this.setState(state => ({
            lead_plans: [...state.lead_plans, {
                id: Date.now(),
                year: year,
                probability: probability,
                plan2: plan2,
                plan3: plan3,
                fee: fee,
                addcosts: addcosts
            }]
        }));

        // here i am sending that data to parent component.
        this.props.plansClick({
                id: Date.now(),
                year: year,
                probability: probability,
                plan2: plan2,
                plan3: plan3,
                fee: fee,
                addcosts: addcosts
            }
        );
    }

// here i am doing delete process in child component
handleRemoveFields = () => {
        const {updateMode, lead_plan_row} = this.state;
        this.setState(prevState => ({lead_plans: prevState.lead_plans.filter(lead_offer_rec => lead_offer_rec !== lead_plan_row)}));
    };

// updating in child component
const {lead_id, lead_plans, year, probability, plan2, plan3, fee} = this.state;
            const new_lead = {
                id: lead_id,
                year,
                probability,
                plan2,
                plan3,
                fee,
            };
            const updated_lead_plans = lead_plans.map((lead) => lead.id === lead_id ? new_lead : lead);
            this.setState({
                lead_plans: updated_lead_plans,
                year: '',
                probability: '',
                plan2: '',
                plan3: '',
                fee: '',
                addcosts: '',
                newFieldsEditMode: false,
                LeadPlanSaveUpdateDialogOpen: false
            });

Parent Component:

 // parent component method.
    handlePlansClick = (planData) => {
        // this is parent componet, here i need to do update, delete the array object which got updation and deletion in child component
        // it alwaya adds item right now.
        this.setState(state => ({
            lead_plans: [...state.lead_plans, planData]
        }));
    }

I need to do all these processes in my parent component too.

Is there more good way to deal with such situation?

How I can get updated, edited, removed item and operation in parent component too?

So both child and parent show the same array component data in arrays.

You should apply a single source of truth principle here. Update the data in the parent only (using a callback passed to the child, as you're doing currently), and then pass the result as a prop to the child. This way the data will always be in sync in both components.

EDIT:

 // parent component method.
    handlePlansClick = (planData) => {
        // this is parent componet, here i need to do update, delete the array object which got updation and deletion in child component
        // it alwaya adds item right now.
        this.setState(state => ({
            lead_plans: [...state.lead_plans, planData]
        }));
    }

Now you pass this function to the child as a prop along with the data:

<Child handlePlansClick={this.handlePlansClick} lead_plans={this.state.lead_plans}/>

Don't use the child's state, just the lead_plans passed from the parent.

BTW, you should be using camelCase for the variable names.

To pass data from child to parent you can write code like below and you will get data in parent.

 Class Child {
        const passDataToParent =() =>{
           const sampleObj = {"name": "Xyz","contact":98739793};
           this.props.receiveChildData(sampleObj );
        }; 
 } 



Class Parent{
    const storeChildData = (dataReceivedFromChild) =>{
         console.log("Received child data",storeChildData)
    }

    render(){
       return (<Child receiveChildData={this.storeChildData}>);
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM