Itay Braha
Itay Braha

Reputation: 536

React Suspense causes router props to be undefined

I use Suspense as the following:

<Route
          path="/courses"
          render={() => (
            <Suspense fallback={HomePage}>
              <Courses />
            </Suspense>
          )}
        />

then, on Courses component, I try accessing the router props as the following:

<Link
            to={{
              pathname: this.props.match.url + "/" + course.id,
              search: "?title=" + course.title,
            }}
            key={course.id}
          >

However, router props turned into undefined. Accessing these props has been possible until I tried adding this React.lazy loading.

I guess that since now Suspense is the component loaded, it receives all the routing props and does not pass them on to my component, but that's just a guess.

to solve it, I also tried the spread operator syntax: e.g <Courses {...props} /> - which didn't work.

How do I access the router props while using React.lazy?

Thanks In Advance!

Upvotes: 0

Views: 895

Answers (1)

UjinT34
UjinT34

Reputation: 4987

You need to pass the props down:

<Route
      path="/courses"
      render={(props) => (
        <Suspense fallback={HomePage}>
          <Courses {...props}/>
        </Suspense>
      )}
    />

Or use withRouter HOC

For functional components you can use useRouteMatch

Upvotes: 3

Related Questions