bradstiff / react-app-location

A package to avoid repetition with Routes and URLs, and reduce boilerplate with location param parsing in React Apps
MIT License
97 stars 8 forks source link

Having trouble protecting routes using MyLocation.toRoute({render:myFunc()}) #2

Closed YM-KA closed 5 years ago

YM-KA commented 5 years ago

I'm refactoring code to be DRY by using react-app-link to handle routes. For public routes this woks like a charm! But most of my routes are protected and I am having trouble protecting my routes when using MyLocation.toRoute({render}).

When trying to protect the route I get a lot of cryptic error messages. Unfortunately the ract-app-link documentation has no examples for the renderOptions "render" .

//Link object
const wholeNbr = Yup.number().integer().positive()
const MyLocation = new Location('/doc/:id', {id : wholeNbr.required()})

//Unprotected route - Working code:
{ MyLocation.toRoute({ component: MyComponent, invalid: NotFoundPage }, true) }

//Protected route - Not working:
const privateLocation = (isAuthenticated, Component) => (
  isAuthenticated ? 
  (
    <Component />
  ):(
    <Redirect to="/" /> //redirect to login page
  )
)
...
<Router history={history}>
  ...
  <Switch>
  ...
  { CategoryLocation.toRoute({ render: privateLocation(isAuthenticated, MyComponent), invalid: NotFoundPage }, true) }
  ...
  </Switch>
</Router>

I expect the component to render, but receive the error "TypeError: _render is not a function"

bradstiff commented 5 years ago

You are not passing a function to your render prop. Try the following instead: { CategoryLocation.toRoute({ render: () => privateLocation(isAuthenticated, MyComponent), invalid: NotFoundPage }, true) }

YM-KA commented 5 years ago

Thank you for the prompt reply, what a basic error! Many thanks for pointing it out to me! (^__^)/