reactjsreduxreact-hoc

parent to child communication - reactjs with tsx and redux connect


I have started learning react.

i'm not sure how to pass values between (parent-child)components when redux-connect is being used.

works well when i directly export the class without a connect or compose

error

Type '{ dataFromParent: string; parentCallback: (data: any) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<unknown, any, any>> & Readonly<unknown> & Readonly<{ children?: ReactNode; }>'.
  Property 'dataFromParent' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<unknown, any, any>> & Readonly<unknown> & Readonly<{ children?: ReactNode; }>'.

parent.tsx

 <Child
   dataFromParent={this.state.data}
   parentCallback={this.parentCalled}
 />

child.tsx

import React from "react";
import "./Child.css";
import TreeView from "@material-ui/lab/TreeView";
import TreeItem from "@material-ui/lab/TreeItem";
import {
  Button,
  withStyles,
  WithStyles,
  Theme,
  StyleRules,
  createStyles
} from "@material-ui/core";
import { connect } from "react-redux";
import compose from "recompose/compose";
import { AppState } from "Store";

interface MyProps extends WithStyles<typeof styles> {
  dataFromParent: any; // value from parent
  parentCallback: (val: string) => void; // sending value to parent
}

// state
interface MyState {}

const styles = (theme: Theme): StyleRules => createStyles({});

class Child extends React.Component<MyProps, MyState> {
  constructor(props: any) {
    super(props);
    this.state = {};
    this.callParent = this.callParent.bind(this);
  }

  componentDidMount() {}

  public callParent() {
    // child to parent
    this.props.parentCallback("value sent from child");
  }
  public render() {
    return (
      <div className="treeStyle">
        <div> data from parent: {this.props.dataFromParent}</div>
        <Button onClick={this.callParent}>
          send to parent
        </Button>
       </div>
    );
  }
}

const mapStateToProps = (state: AppState) => ({});
export default compose(withStyles(styles), connect(mapStateToProps, {}))(Child);

Solution

  • You can achieve it without using recompose as well for example:

    export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(Child));
    

    Additionally you may want to change props: any to props: MyProps to avoid any warnings by tslint/eslint