trendmicro-frontend / react-sidenav

React SideNav component
https://trendmicro-frontend.github.io/react-sidenav/
MIT License
349 stars 105 forks source link

Cannot read property 'location' of undefined #8

Closed ivanvorona closed 5 years ago

ivanvorona commented 5 years ago

Hello, I got below error and here are my dependencies:

"dependencies": { "@trendmicro/react-sidenav": "^0.4.5", "apollo-boost": "^0.1.16", "graphql": "^14.0.2", "hamoni-sync": "^0.6.2", "react": "^16.5.2", "react-apollo": "^2.1.11", "react-dom": "^16.5.0", "react-router": "^4.3.1", "react-scripts": "1.1.5", "react-table": "^6.8.6" },

do i need to downgrade react-router?

Full error message:

TypeError: Cannot read property 'location' of undefined new Router node_modules/react-router/es/Router.js:31 28 | } 29 | 30 | return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {

31 | match: _this.computeMatch(_this.props.history.location.pathname) 32 | }, _temp), _possibleConstructorReturn(_this, _ret); 33 | } 34 | View compiled constructClassInstance node_modules/react-dom/cjs/react-dom.development.js:11624 11621 | } 11622 | } 11623 | 11624 | var instance = new ctor(props, context); 11625 | var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; 11626 | adoptClassInstance(workInProgress, instance); 11627 | View compiled updateClassComponent node_modules/react-dom/cjs/react-dom.development.js:13346 13343 | if (current$$1 === null) { 13344 | if (workInProgress.stateNode === null) { 13345 | // In the initial pass we might need to construct the instance. 13346 | constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime); 13347 | mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime); 13348 | shouldUpdate = true; 13349 | } else { View compiled beginWork node_modules/react-dom/cjs/react-dom.development.js:13945 13942 | { 13943 | var _Component6 = workInProgress.type; 13944 | var _unresolvedProps3 = workInProgress.pendingProps; 13945 | return updateClassComponent(current$$1, workInProgress, _Component6, _unresolvedProps3, renderExpirationTime); 13946 | } 13947 | case ClassComponentLazy: 13948 | { View compiled performUnitOfWork node_modules/react-dom/cjs/react-dom.development.js:16249 16246 | startProfilerTimer(workInProgress); 16247 | } 16248 | 16249 | next = beginWork(current$$1, workInProgress, nextRenderExpirationTime); 16250 | 16251 | if (workInProgress.mode & ProfileMode) { 16252 | // Record the render duration assuming we didn't bailout (or error). View compiled workLoop node_modules/react-dom/cjs/react-dom.development.js:16287 16284 | if (!isYieldy) { 16285 | // Flush work without yielding 16286 | while (nextUnitOfWork !== null) { 16287 | nextUnitOfWork = performUnitOfWork(nextUnitOfWork); 16288 | } 16289 | } else { 16290 | // Flush asynchronous work until the deadline runs out of time. View compiled HTMLUnknownElement.callCallback node_modules/react-dom/cjs/react-dom.development.js:145 142 | window.event = windowEvent; 143 | } 144 | 145 | func.apply(context, funcArgs); 146 | didError = false; 147 | } 148 | View compiled invokeGuardedCallbackDev node_modules/react-dom/cjs/react-dom.development.js:195 192 | // Synchronously dispatch our fake event. If the user-provided function 193 | // errors, it will trigger our global error handler. 194 | evt.initEvent(evtType, false, false); 195 | fakeNode.dispatchEvent(evt); 196 | 197 | if (didError) { 198 | if (!didSetError) { View compiled invokeGuardedCallback node_modules/react-dom/cjs/react-dom.development.js:248 245 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { 246 | hasError = false; 247 | caughtError = null; 248 | invokeGuardedCallbackImpl$1.apply(reporter, arguments); 249 | } 250 | 251 | /** View compiled replayUnitOfWork node_modules/react-dom/cjs/react-dom.development.js:15578 15575 | // Replay the begin phase. 15576 | isReplayingFailedUnitOfWork = true; 15577 | originalReplayError = thrownValue; 15578 | invokeGuardedCallback(null, workLoop, null, isYieldy); 15579 | isReplayingFailedUnitOfWork = false; 15580 | originalReplayError = null; 15581 | if (hasCaughtError()) { View compiled renderRoot node_modules/react-dom/cjs/react-dom.development.js:16381 16378 | 16379 | var failedUnitOfWork = nextUnitOfWork; 16380 | if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { 16381 | replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy); 16382 | } 16383 | 16384 | // TODO: we already know this isn't true in some cases. View compiled performWorkOnRoot node_modules/react-dom/cjs/react-dom.development.js:17220 17217 | cancelTimeout(timeoutHandle); 17218 | } 17219 | var isYieldy = false; 17220 | renderRoot(root, isYieldy, isExpired); 17221 | finishedWork = root.finishedWork; 17222 | if (finishedWork !== null) { 17223 | // We've completed the root. Commit it. View compiled performWork node_modules/react-dom/cjs/react-dom.development.js:17128 17125 | } 17126 | } else { 17127 | while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && (minExpirationTime === NoWork || minExpirationTime >= nextFlushedExpirationTime)) { 17128 | performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, true); 17129 | findHighestPriorityRoot(); 17130 | } 17131 | } View compiled performSyncWork node_modules/react-dom/cjs/react-dom.development.js:17100 17097 | } 17098 | 17099 | function performSyncWork() { 17100 | performWork(Sync, null); 17101 | } 17102 | 17103 | function performWork(minExpirationTime, dl) { View compiled requestWork node_modules/react-dom/cjs/react-dom.development.js:16988 16985 | 16986 | // TODO: Get rid of Sync and use current time? 16987 | if (expirationTime === Sync) { 16988 | performSyncWork(); 16989 | } else { 16990 | scheduleCallbackWithExpirationTime(root, expirationTime); 16991 | } View compiled scheduleWork node_modules/react-dom/cjs/react-dom.development.js:16782 16779 | // ...unless this is a different root than the one we're rendering. 16780 | nextRoot !== root) { 16781 | var rootExpirationTime = root.expirationTime; 16782 | requestWork(root, rootExpirationTime); 16783 | } 16784 | if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { 16785 | // Reset this back to zero so subsequent updates don't throw. View compiled scheduleRootUpdate node_modules/react-dom/cjs/react-dom.development.js:17470 17467 | } 17468 | enqueueUpdate(current$$1, update); 17469 | 17470 | scheduleWork(current$$1, expirationTime); 17471 | return expirationTime; 17472 | } 17473 | View compiled updateContainerAtExpirationTime node_modules/react-dom/cjs/react-dom.development.js:17497 17494 | container.pendingContext = context; 17495 | } 17496 | 17497 | return scheduleRootUpdate(current$$1, element, expirationTime, callback); 17498 | } 17499 | 17500 | function findHostInstance(component) { View compiled updateContainer node_modules/react-dom/cjs/react-dom.development.js:17524 17521 | var current$$1 = container.current; 17522 | var currentTime = requestCurrentTime(); 17523 | var expirationTime = computeExpirationForFiber(currentTime, current$$1); 17524 | return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback); 17525 | } 17526 | 17527 | function getPublicRootInstance(container) { View compiled ReactRoot../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render node_modules/react-dom/cjs/react-dom.development.js:17786 17783 | if (callback !== null) { 17784 | work.then(callback); 17785 | } 17786 | updateContainer(children, root, null, work._onCommit); 17787 | return work; 17788 | }; 17789 | ReactRoot.prototype.unmount = function (callback) { View compiled (anonymous function) node_modules/react-dom/cjs/react-dom.development.js:17926 17923 | if (parentComponent != null) { 17924 | root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback); 17925 | } else { 17926 | root.render(children, callback); 17927 | } 17928 | }); 17929 | } else { View compiled unbatchedUpdates node_modules/react-dom/cjs/react-dom.development.js:17351 17348 | isUnbatchingUpdates = false; 17349 | } 17350 | } 17351 | return fn(a); 17352 | } 17353 | 17354 | // TODO: Batching should be implemented at the renderer level, not within View compiled legacyRenderSubtreeIntoContainer node_modules/react-dom/cjs/react-dom.development.js:17922 17919 | }; 17920 | } 17921 | // Initial mount should not be batched. 17922 | unbatchedUpdates(function () { 17923 | if (parentComponent != null) { 17924 | root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback); 17925 | } else { View compiled render node_modules/react-dom/cjs/react-dom.development.js:17981 17978 | return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); 17979 | }, 17980 | render: function (element, container, callback) { 17981 | return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); 17982 | }, 17983 | unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) { 17984 | !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0; View compiled ./src/index.js src/index.js:235 232 | 233 | ); 234 | 235 | render(, document.getElementById("root")); 236 | 237 | 238 | // WEBPACK FOOTER // View compiled ▶ 6 stack frames were collapsed.

cheton commented 5 years ago

Check below if you have the similar issue: https://stackoverflow.com/a/42895076/2264306

ivanvorona commented 5 years ago

Hello, I tried this solution yesterday, it helped me get rid of error but it doesn't render any sidebar, just empty screen with no error: http://165.227.44.17:3000 Do you have any other advice?

cheton commented 5 years ago

Hi @ivanvorona

Do you have a complete sample code? I don't think it can be correctly rendered as your code from line #184-226 does not return a React component, and the line #231 was doing nothing as well.

image

ivanvorona commented 5 years ago

Hi @cheton ,i was just doing it based on project setup instructions, EagleClients should render the table view.(it does now but i am trying to get it under the sidebar controls - expecting more tables like this later and need different sections) the source code can be cloned from here: https://eagleinvsys.visualstudio.com/DIS_UI/_git/DIS_UI

Thank you for your time.

cheton commented 5 years ago

Declare a functional component and render it inside your App:

import React from "react";
import { render } from "react-dom";

import './styles/index.css';
// eslint-disable-next-line
//import App from './App';
//import registerServiceWorker from './registerServiceWorker';
import ApolloClient from "apollo-boost";
import { ApolloProvider,Query } from "react-apollo";
import gql from "graphql-tag";
//import Client from './components/Client'
import ReactTable from "react-table";
import 'react-table/react-table.css'
import SideNav, { Toggle, Nav, NavItem, NavIcon, NavText } from '@trendmicro/react-sidenav';
//import { Router, Route, Switch } from 'react-router'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
// Be sure to include styles at some point, probably during your bootstraping
import '@trendmicro/react-sidenav/dist/react-sidenav.css';

const client = new ApolloClient({
   uri: "http://165.227.44.17:5000/graphql"
//   uri: "https://graphql-demo.commonsware.com/0.2/graphql"
// uri: "https://w5xlvm3vzz.lp.gql.zone/graphql"
});
/*
client.query({
  query: gql`
      {
    allClients {
  edges {
    node {
      NAME
      CODE
      TIMEZONE
    }
  }
}
      }
  `
}).then(response => console.log(response.data.allClients))
  .catch(error => console.error(error));
*/

const EagleClients = () => (
  <Query
    query={gql`
      {
    allClients {
  edges {
    node {
      CODE
      NAME
      TIMEZONE
      STARTDate
    }
  }
}
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return `Error!: ${error}`;;

      const clientsToRender = data.allClients.edges;
      console.log(clientsToRender);
      //console.log(typeof clientsToRender);
      var i = 0;
      return (
            <div>

        <ReactTable
          data={clientsToRender}
        //  noDataText="Oh Noes!"
          columns={[
            {
              Header: "Client",
              columns: [
                {
                  Header: "N",
                  id: "N",
                  accessor: d =>  i+1,
                  maxWidth: 50

                },
                {
                  Header: "Code",
                  id: "lastName",
                  accessor: d =>  clientsToRender[i]['node']['CODE'],
                  Footer: (
                    <span>
                      <strong>Footer: Some analytic info TBD </strong>{" "}
                    </span>
                )

        },
                {
                  Header: "Name",
                  id: "clientName",
                  accessor: d =>  clientsToRender[i]['node']['NAME']
                },
                {
                  Header: "TimeZone",
                  id: "timeZone",
                  accessor: d =>  clientsToRender[i]['node']['TIMEZONE'],
                  maxWidth: 200
                },
                {
                  Header: "STARTDate",
                  id: "startDate",
                  accessor: d =>  clientsToRender[i++]['node']['STARTDate']
                }
              ]
            }]}
          defaultPageSize={50}
          filterable
          style={{
            height: "600px" // This will force the table body to overflow and scroll, since there is not enough room
          }}
          className="-striped -highlight"
          SubComponent={row => {
            return (
              <div style={{ padding: "20px" }}>
                <em>
                  List of client Interfaces from in another React
                  Table!
                </em>
                <br />
                <br />
                <ReactTable
                  data={[
{
            InterfaceName: "SomeName",
            InterfaceDesc: "SomeDesc"},
        {
            InterfaceName: "SomeName1",
            InterfaceDesc: "SomeDesc2"

        }
]}
                  columns={[
            {
              Header: "Interfaces",
              columns: [
                {
                  Header: "N",
                  id: "N",
                  accessor: d =>  i+1,
                  maxWidth: 50                },
                {
                  Header: "Code",
                  id: "intCode",
                  accessor: d =>  data.InterfaceName
                },
                {
                  Header: "Name",
                  id: "intName",
//                  accessor: d =>  clientsToRender[i]['node']['NAME']
                }
              ]}]}
                  defaultPageSize={3}
                  showPagination={false}
                  SubComponent={() => <div style={{padding: '10px'}}>Vendor Info</div>}
/*                  SubComponent={row => {
                    return (
                      <div style={{ padding: "20px" }}>
                        Another Sub Component!
                      </div>
                    );
                  }}*/
                />
              </div>
            );}}
        />
        <br />

            </div>
);

    }}
  </Query>
);

const Container = () => (
    <Router>
        <Route render={({ location, history }) => (
            <React.Fragment>
                <SideNav
                     onSelect={(selected) => {
                        const to = '/' + selected;
                        if (location.pathname !== to) {
                            history.push(to);
    console.log(location.pathname);
    console.log(to);

                        }
                    }}
                >
                    <SideNav.Toggle />
                    <SideNav.Nav defaultSelected="home">
                        <NavItem eventKey="home">
                            <NavIcon>
                                <i className="fa fa-fw fa-home" style={{ fontSize: '1.75em' }} />
                            </NavIcon>
                            <NavText>
                                Home
                            </NavText>
                        </NavItem>
                        <NavItem eventKey="devices">
                            <NavIcon>
                                <i className="fa fa-fw fa-device" style={{ fontSize: '1.75em' }} />
                            </NavIcon>
                            <NavText>
                                Devices
                            </NavText>
                        </NavItem>
                    </SideNav.Nav>
                </SideNav>
                <main>
                    <Route path="/" exact component={props => <EagleClients />} />
                    <Route path="/home" component={props => <EagleClients />} />
                    <Route path="/devices" component={props => <EagleClients />} />
                </main>
            </React.Fragment>
        )}
        />
    </Router>
);

const App = () => (
  <ApolloProvider client={client}>
    <div>
      <Container />
      <EagleClients />
    </div>
  </ApolloProvider>
);

render(<App />, document.getElementById("root"));
ivanvorona commented 5 years ago

got it, thank you for your help!

PritamBhanji08 commented 4 years ago

@cheton I am also getting same error: TypeError: Cannot read property 'location' of undefined Error on : node_modules/react-router/esm/react-router.js:46 ` import React from 'react' import SideNav, { Toggle, Nav, NavItem, NavIcon, NavText } from '@trendmicro/react-sidenav' import ClickOutside from '../components/ClickOutside' import WireFraudComponent from '../components/WireFraudComponent' import { Router, Route } from "react-router";

export default class MenuContainer extends React.Component { constructor(props) { super(props) this.state = { expanded: false } } menuItemClicked = (selected) => { console.log(Menu ${selected} clicked)

}

render() { return ( <>

<ClickOutside
    onClickOutside={() => {
        this.setState({ expanded: false });
    }}
>
<Router>
  <Route render={({ location, history }) => (
    <React.Fragment>
      <SideNav
      expanded={this.state.expanded}
      onToggle={(expanded) => {
          this.setState({ expanded });
      }}
      onSelect={(selected) => {
        // Add your code here
        // this.menuItemClicked(selected)
        const to = '/' + selected;
        console.log(location)
        if (location.pathname !== to) {
          history.push(to);
        }
      }}
      >
        <SideNav.Toggle />
          <SideNav.Nav defaultSelected="orders">
              <NavItem eventKey="orders">
                  <NavIcon>
                      <i className="material-icons" style={{ fontSize: '1.75em' }}>insert_drive_file</i>
                  </NavIcon>
                  <NavText>
                      Orders
                  </NavText>
              </NavItem>
              <NavItem eventKey="wire-fraud">
                  <NavIcon>
                      <i className="material-icons" style={{ fontSize: '1.75em' }}>contacts</i>
                  </NavIcon>
                  <NavText>
                      Wire Fraud Support
                  </NavText>
              </NavItem>
              <NavItem eventKey="help">
                  <NavIcon>
                      <i className="material-icons" style={{ fontSize: '1.75em' }}>live_help</i>
                  </NavIcon>
                  <NavText>
                      Help & FAQ
                  </NavText>
              </NavItem>

              <NavItem eventKey="admin">
                  <NavIcon>
                      <i className="material-icons" style={{ fontSize: '1.75em' }}>account_box</i>
                  </NavIcon>
                  <NavText>
                      Administration <i className="material-icons">keyboard_arrow_down</i>
                  </NavText>
                  <NavItem eventKey="admin/team">
                      <NavText>
                        <i className="material-icons">supervisor_account</i> Team directory
                      </NavText>
                  </NavItem>
                  <NavItem eventKey="admin/escrow">
                      <NavText>
                        <i className="material-icons">library_books</i> Escrow accounts
                      </NavText>
                  </NavItem>
                  <NavItem eventKey="admin/integrations">
                      <NavText>
                        <i className="material-icons">sync</i>  Integrations
                      </NavText>
                  </NavItem>
              </NavItem>
          </SideNav.Nav>
        </SideNav>
        <main>
          <Route path="/wire-fraud" component={props => <WireFraudComponent />} />
        </main>
      </React.Fragment>
    )} />
    </Router>
  </ClickOutside>
</>
)

}

}`

PritamBhanji08 commented 4 years ago

This is another file which is root file App.js where i have defined router as well import React from 'react' import LoginContainer from '../containers/LoginContainer' import { Router, Route } from "react-router"; import VerifyContainer from '../containers/VerifyContainer'; import OrdersContainer from '../containers/OrdersContainer'; import NoMatch from './NoMatch'; import { createBrowserHistory } from "history";

class App extends React.Component { render() { const history = createBrowserHistory() return ( < Router history={history}> < Route exact path="/" component={LoginContainer}/> < Route exact path="/login" component={LoginContainer}/> < Route path="/verify" component={VerifyContainer}/> < Route path="/orders" component={OrdersContainer}/> ) } }

export default App;