0

I have been trying to call this function onCountRowsCompanies of prinWhole.js so that I can display the number of companies in the dashboard.js but could not. Can someone please help me out here?

printWhole.js

import React, { Component } from "react";
        import axios from "axios";
        import Logo from "../../common/logo";
        import {Link} from "react-router-dom";
        import "../style.css";

        class printWhole extends Component {
          constructor(props) {
            super(props);
            this.state = { company: [] };
            this.onPrint = this.onPrint.bind(this);
            this.onCountRowsCompanies = this.onCountRowsCompanies.bind(this);
          }
          componentDidMount() {
            axios
              .get("http://localhost:4000/api/company")
              .then(response => {
                this.setState({ company: response.data });
              })
              .catch(function(error) {
                console.log(error);
              });
          }
          componentDidUpdate() {
            axios
              .get("http://localhost:4000/api/company")
              .then(response => {
                this.setState({ company: response.data });
              })
              .catch(function(error) {
                console.log(error);
              });
          }

          onPrint = e => {
            e.preventDefault();
            document.getElementById("hide").style.visibility="hidden";
            window.print();
            document.getElementById("hide").style.visibility="visible";
          };

        /**This is the function onCountRowsCompanies that I want to call in Dashboard.js to display the number of companies**/
          onCountRowsCompanies = e => {
            e.preventDefault();
            var totalRowCount = 0;
            var rowCount = 0;
            var table = document.getElementById("css-serial");
            var rows = document.getElementsByTagName("tr");
            for( var i = 0; i < rows.length; i++){
              totalRowCount++;
              if(rows[i].getElementsByTagName("td").length > 0){
                rowCount++;
              }
            }

            let message = "Total number of companies so far " + rowCount;
            //alert(message);
            document.getElementById("displayMessage").innerHTML = message; 
          };

          render() {
            const company = this.state.company;

            return (
              <div className="mt-5 mb-5">
              <button className="btn btn-info ml-5" onClick={this.onPrint} id="printButton">
              Print
            </button>
             <Link
                    to="/api/company"
                    className="btn btn-dark"
                    style={{ marginLeft: "75%" }}
                    id="hide"
                  >
                    Back to List
                  </Link>
                  <div className="mt-4 mb-4 p-3" style={{ border: "1px solid black"}}>
              <Logo/>
                <h4 align="center" style={{ marginTop: "20px" }}>
                  Company List
                </h4>
                  <table className="table table-bordered mb-4 mt-4 text-center" id="css-serial">
                 <tbody>
                      <tr>
                        <th>No</th>
                        <th>Company Name</th>
                        <th>Contact Person</th>
                        <th>Contact Number</th>
                        <th>Alternate Contact Number</th>
                        <th>Email</th>
                        <th>Fax</th>
                        <th>Address</th>
                      </tr>

                      {company.map(
                        ({
                          _id,
                          companyname,
                          contactperson,
                          contactno,
                          alternatecontactno,
                          email,
                          fax,
                          address
                        }) => (

                            <tr key={company._id}>
                              <td></td>
                              <td>{companyname}</td>
                              <td>{contactperson}</td>
                              <td>{contactno}</td>
                              <td>{alternatecontactno}</td>
                              <td>{email}</td>
                              <td>{fax}</td>
                              <td>{address}</td>
                            </tr>
                          )
                      )}
                 </tbody>
                </table>
                <button className="btn btn-primary" onClick={this.onCountRowsCompanies}>Result</button>
                  <div id="displayMessage" className="mt-4 mb-4"></div>
                <p className="text-center">Copyright &copy; {new Date().getFullYear()} Nice Infotech</p>
              </div>
                  </div>

            );
          }
        }

        export default printWhole;

dashboard.js

        import React, { Component } from "react";
        import { Link } from "react-router-dom";
        import PropTypes from "prop-types";
        import { connect } from "react-redux";
        import { getCurrentProfile, deleteAccount } from "../../actions/profileActions";
        import Spinner from "../common/Spinner";
        import ProfileActions from "./ProfileActions";
        // import Experience from "./Experience";
        // import Education from "./Education";
        import "../css/Dashboard.css";
        // import { onCountRowsCompanies } from "../master/company/printwhole";


        class Dashboard extends Component {
          componentDidMount() {
            this.props.getCurrentProfile();
          }

          onDeleteClick(e) {
            this.props.deleteAccount();
          }

          render() {
            const { user } = this.props.auth;
            const { profile, loading } = this.props.profile;

            let dashboardContent;

            if (profile === null || loading) {
              dashboardContent = <Spinner />;
            } else {
              // Check if logged in user has profile data
              if (Object.keys(profile).length > 0) {
                dashboardContent = (
                  <div>
                    {/** This is where I want to display the number of Companies */}
                  </div>
                );
              } else {
                // User is logged in but has no profile
                dashboardContent = (
                  <div>
                    <p className="lead text-muted">Welcome {user.name}</p>
                    <p>You have not yet setup a profile, please add some info</p>
                    <Link to="/create-profile" className="btn btn-lg btn-info">
                      Create Profile
                    </Link>
                  </div>
                );
              }
            }

            return <div>{dashboardContent}</div>;
          }
        }

        Dashboard.propTypes = {
          getCurrentProfile: PropTypes.func.isRequired,
          deleteAccount: PropTypes.func.isRequired,
          auth: PropTypes.object.isRequired,
          profile: PropTypes.object.isRequired
        };

        const mapStateToProps = state => ({
          profile: state.profile,
          auth: state.auth
        });

        export default connect(
          mapStateToProps,
          { getCurrentProfile, deleteAccount}
        )(Dashboard);
Amol B Jamkar
  • 1,227
  • 10
  • 19
  • You can put this function in a common parent, or you can use the [context API](https://reactjs.org/docs/context.html) – soywod Apr 23 '19 at 08:18

2 Answers2

0

You could do this by using a ref to the child component and then calling the method. However, this is not the recommended way to use React.

See this detailed answer: https://stackoverflow.com/a/37950970/1783174

publicJorn
  • 2,404
  • 1
  • 20
  • 30
0

You probably don't want to do that. I don't expect this to be the right answer for you but have you heard of state management?

Try Redux, this could be very easy to achieve.

Follow these steps, after you integrate your project with Redux: , and perhaps Redux-thunk / Redux-saga for handling side effects (api calls):

  1. When you want to call api, dispatch an action to redux store, handle api call with Redux-thunk / Redux-saga, update store with received data.

  2. connect your component with Redux, data available in Redux store change will trigger re-render on this component.

I know this will be a lot of work but it's gonna save you a lot more time in the future.

Pho Huynh
  • 1,497
  • 3
  • 13
  • 23