Friday 28 January 2022

Child to parent communication

 import React, { Component } from "react";


class Child extends Component {

  constructor(props) {

    super(props);


    this.state = {

      name: "Pankaj",

      city: "Mumbai",

    };

  }


  sendData = () => {

    this.props.updateParentState(this.state.name, this.state.city);

  };


  render() {

    return (

      <div className="card">

        <div className="card-header bg-primary text-white">

          <h2>Child Component</h2>

        </div>


        <div className="card-body">

          <button className="btn btn-primary" onClick={this.sendData}>

            Send Data to Parent

          </button>

        </div>

      </div>

    );

  }

}

export default Child;


import React, { Component } from "react";

import Child from "./Child";


class Parent extends Component {

  constructor(props) {

    super(props);


    this.state = {

      name: "",

      city: "",

    };

  }


  updateParentState = (n, c) => {

    this.setState({

      name: n,

      city: c,

    });

  };


  render() {

    return (

      <div className="container mt-5">

        <div className="row">

          <div className="col">

            <div className="card">

              <div className="card-header bg-dark text-white">

                <h2>Parent Component</h2>

              </div>

              <div className="card-body">

                <Child updateParentState={this.updateParentState} />

              </div>

              <div className="card-footer">

                <p>Name:{this.state.name}</p>

                <p>City:{this.state.city}</p>

              </div>

            </div>

          </div>

        </div>

      </div>

    );

  }

}

export default Parent;

Note: We are transferring child state data to parent. Hence both parent & child component must have state


PostedBy: pankaj_bhakre

No comments:

Post a Comment