0
votes

I have a ReactJS app that I'm building from a template. I'm not familiar with react, let alone how the components are loaded with this pattern.

How can I access the history from within a nested component route?

app.js

const routes = {
  path: '/',
  indexRoute: { onEnter: (nextState, replace) => replace('/login') },
  childRoutes: [
    require('./routes/ticketing').default,
    require('./routes/promotions').default,
    ...
  ]
};

ReactDOM.render((
  <Provider store={store}>
    <Router
      history={history}
      routes={routes}
    />
  </Provider>
), document.getElementById('app'));

routes/ticketing/index.js

export default {
  path: 'ticketing',
  component: require('../../components/common/Layout').default,

  indexRoute: { onEnter: (nextState, replace) => replace('/ticketing/printtickets') },

  childRoutes: [
    {
      path: 'printtickets',
      getComponent(nextState, cb){
        System.import('./containers/printtickets').then((m)=> {
          cb(null, m.default)
        })
      }
    }
    ,
    ...
  ]
};

routes/ticketing/containers/printtickets.js

import React from 'react'

export default class PrintTickets extends React.Component {

  componentWillMount(){
    const { history } = this.props; // THIS IS NULL
    history.replaceState(null, 'analytics/dashboard') // ERROR
  }

  render() {
    return (
      <div />
    )
  }
}
1

1 Answers

2
votes

You can wrap your components with the withRouter HOC to get access to the history object.

More details here: https://reacttraining.com/react-router/web/api/withRouter