8 Child to Parent Communication in ReactJS

src/Parent.tsx: 
 import React, { Component } from "react";
import Child from "./Child";

interface IState {
  msg: string;
}

interface IProps {}

class Parent extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      msg: "ReactJS",
    };
  }

  myFun = (data: any): void => {
    this.setState({
      msg: data,
    });
  };

  render() {
    return (
      <React.Fragment>
        <h1>{this.state.msg}</h1>
        <Child key1={this.myFun}> </Child>
      </React.Fragment>
    );
  }
}

export default Parent;

src/Child.tsx: 
 import React, { Component } from "react";

interface IState {}

interface IProps {
  key1: (data: any) => void;
}

class Child extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>
        <button
          onClick={() => {
            this.props.key1("ReactJS with TypeScript");
          }}
        >
          {" "}
          Change{" "}
        </button>
      </React.Fragment>
    );
  }
}

export default Child;

Output (Before Click): 
Child to Parent Communication in ReactJS

Output (After Click): 
Child to Parent Communication in ReactJS After Click
Previous
Next Post »