3

I have the following code:

  <BrowserRouter>
    <IndexComponent />
  </BrowserRouter>

Inside I have a switch with all the routes.

IndexComponent.js:

<Switch >
  <Route exact path="/course_info/:id" component={CourseInfoPage} />
    <Route exact path="/"  component={Main} />
    .
    .
    .
</Switch>

I would like to have access to location prop in IndexComponent in order add transition animation like so:

<CSSTransition key={location.key} classNames="fade" timeout={300}>
  <Switch location={location}>
    <Switch >
      <Route exact path="/course_info/:id" component={CourseInfoPage} />
        <Route exact path="/"  component={Main} />
        .
        .
        .
    </Switch>
  </CSSTransition>
</TransitionGroup>

As you can see, I need the location prop inside IndexComponent. But it is not present there. Why not, and how should I add it?

D M
  • 1,689
  • 5
  • 14
  • 29
  • 1
    This might help you https://stackoverflow.com/questions/44009618/uncaught-typeerror-cannot-read-property-push-of-undefined-react-router-dom/44009788#44009788 – Shubham Khatri Apr 06 '18 at 17:53

1 Answers1

3

I think the only way to pass the location prop down is to use <Route />

  <BrowserRouter>
    <Route render={(props) => <IndexComponent location={props.location}/> }> </Route>
  </BrowserRouter>

Then do

<CSSTransition key={this.props.location} classNames="fade" timeout={300}>
Omar
  • 3,044
  • 2
  • 19
  • 31
  • or withRouter HOC, however simply `` will also work – Shubham Khatri Apr 06 '18 at 17:53
  • @ShubhamKhatri if you do `` shouldnt you use `render` instead of `component` so you can acess the `match location history` props etc? – Omar Apr 06 '18 at 18:02
  • with `component` all props will be passed down to IndexComponent, if you use render it gives you back the props in the callback which you can decide to pass down to the component selectively. However mostly you would use render if you need to pass down some custom props. You might check this https://stackoverflow.com/questions/44255415/passing-custom-props-to-router-component-in-react-router-v4/44255850#44255850 – Shubham Khatri Apr 06 '18 at 18:04