Private Route getting called dozens of times in React - javascript

I keep having maximum update depth exceeded errors and I can't figure out why.
I have the following (pared down, it was more complex originally and actually rendered the component) private route in a private route file:
class PrivateRoute extends Component {
render() {
console.log("private route");
return <Redirect to="/login" />;
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withKeycloak(PrivateRoute));
And then in my index.js I have the following:
<Route
render={({ location }) => {
const { pathname } = location;
return (
<TransitionGroup>
<CSSTransition
key={pathname}
classNames="page"
timeout={{
enter: 1000,
exit: 1000
}}
>
<Route
location={location}
render={() => (
<Switch>
<Route path="/login" component={LoginPage} />
<Route path="/signup/" component={Signup} />
<PrivateRoute
exact
path="/cards/"
component={Wrapper}
/>
<PrivateRoute
exact
path="/"
component={Wrapper}
/>
...
This should, as far as I can tell, go to the PrivateRoute component for Wrapper on initial load, and then, redirect to the login page, which should not invoke the private route.
Instead, I see:
52 private route
in my console log.
Why am I being redirected back to PrivateRoute dozens of times? Shouldn't this happen once, and that's it?
There's no redirect to anywhere else on the login page at all. There is a login function, but that requires a button click, which is not happening.
Any idea on why this could be happening?
The error message:
in Lifecycle (created by Context.Consumer)
in Redirect (at PrivateRoute.js:11)
in PrivateRoute (created by Context.Consumer)
in WithKeycloak(PrivateRoute) (created by Context.Consumer)
in Connect(WithKeycloak(PrivateRoute)) (at src/index.js:114)
in Switch (at src/index.js:106)
in Route (at src/index.js:103)
in Transition (created by CSSTransition)
in CSSTransition (at src/index.js:95)
in div (created by TransitionGroup)
Originally, the routes looked more like this:
class PrivateRoute extends Component {
render() {
return (
<Route
{...rest}
render={props =>
<Component {...props} />}
/>
)
}
}

rather than
<PrivateRoute
component={Wrapper}
/>
You want to do something like
<Route exact path="/"
render=(props => (<PrivateRoute exact
path="/"
component={Wrapper}>)) />
Otherwise it will just always render your PrivateRoute

Route component is expected to receive a prop exact in order to only render this component when a match exists.
If not exact prop passed, will render it. And then if another match, with render both, and this is why you are getting redirected everytime.
Since you are using a custom component, you must handle this prop to provide it into the Route component.
to fix it, you can follow #TKol approach for example.
<Route exact path="/"
render=(props => (<PrivateRoute
path="/"
component={Wrapper}>))
/>
This way Route is handling that for you and only will render 1 at time.

Related

Add a component as props inside a Route with react-router-dom

Having the following code:
import { Switch, Route, BrowserRouter as Router } from 'react-router-dom';
export function MyComponent({ list }: MyComponentProps) {
return (
<Router>
<Switch>
<Route path={list[0].url} component={<NextComponent />} />
</Switch>
</Router>
);
}
I want to load a different component on that route.
Version of react-router-dom is 5.2.0.
This code is not working, it appears a red line under <Route path... stating this:
Operator '<' cannot be applied to types 'number' and 'typeof Route'.ts(2365)
(alias) class Route<T extends {} = {}, Path extends string = string>
import Route
Any ideas?
LATER EDIT:
There is an answer stating that replacing that line with component={NextComponent} will get rid of the error message. That's true but is it possible to send props to that component in this case?
For example, for component={<NextComponent someProps={something} />} seems possible but not for component={NextComponent}
In react-router-dom v5 you don't specify the component prop as a JSX literal (the RRDv6 syntax), just pass a reference to the component.
component={NextComponent} instead of component={<NextComponent />}
Code
export function MyComponent({ list }: MyComponentProps) {
return (
<Router>
<Switch>
<Route path={list[0].url} component={NextComponent} />
</Switch>
</Router>
);
}
If you need to pass along additional props then you must use the render prop. This effectively renders an anonymous React component. Don't forgot you may need to also pass along the route props to the rendered components.
export function MyComponent({ list }: MyComponentProps) {
return (
<Router>
<Switch>
<Route
path={list[0].url}
render={props => <NextComponent {...props} something={value} />}
/>
</Switch>
</Router>
);
}
Route render methods

Does react-router-dom automatically pass history object to children components inside Router?

This will probably be a rookie question but does Router component passes down the history object to child components automatically? to demonstrate I have this
App.js ;
const App = () => {
return (
<>
<h1>Hello</h1>
<Router history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/another_route" exact component={AnotherRoute} />
</Switch>
</Router>
</>
);
};
and Home and Another Route components taking advantage of the history prop to re-route without explicitly being passed down to the children via Router.
// Home.js
import React from "react";
const Home = (props) => {
return (
<>
<h3> Hello From home </h3>
<button onClick={() => props.history.push("/another_route")}>
click here to go another route
</button>
</>
);
};
export default Home;
// AnotherRoute.js
import React from "react";
const AnotherRoute = (props) => {
return (
<>
<h3> Hello From this another Route </h3>
<button onClick={() => props.history.push("/")}>
click here to go back
</button>
</>
);
};
export default AnotherRoute;
Everything functioning just fine, but I would like to understand this. I haven't seen it in the documentation explicitly.
here is a codesandbox I created for you to experiment:
https://codesandbox.io/s/react-router-dom-passes-history-object-to-children-automatically-jj7ih
thanks.
Yes
All Route render methods will be passed the same three route props , match
,location,history. So you can use these props in all the components you render with react-router-dom
What are Route render methods?
The recommended method of rendering something with a <Route> is to use children elements. There are, however, a few other methods you can use to render something with a <Route>like
<Route component>
<Route render>
<Route children> function
What is your Route render method in your example?
You have used <Route component> as <Route path="/" exact component={Home} />
Official Docs

React Router: <Redirect push> doesn't update browser url

I'm learning React making a small single page app. Just added react-router-dom today and building it out to do routes and private routes. All is well except for one thing: When the user enters a malformed url in the browser bar, the user should be rerouted to the index (WORKS!), but the browser url bar is not updated on this redirect. Oddly enough, when I hit a private route while not authorized, the redirect DOES update the url bar. What am I missing?
router.js:
const PrivateRoute = ({auth: authenticated, component: Component, ...rest}) => (
<Route {...rest} render={(props) => (
authenticated === true
? <Component {...props} />
: <Redirect to='/login/'/>
)}/>
);
export default function Router() {
const auth = useSelector(isAuthenticated);
return (
<Switch>
<PrivateRoute auth={"auth"} path={"/dashboard/"} component={DashboardContainer}/>
<Route path={"/about/"} component={AboutContainer}/>
<Route path={"/login/"} component={LoginContainer}/>
<Route path={"/terms/"} component={TermsContainer}/>
<Route path={"/"} component={IndexContainer}/>
<Redirect push to={"/"}/>
</Switch>
);
}
I believe your issue is a result of not specifying that the paths should be exact matches, therefore any route will match with your route that is specified as:
<Route path={"/"} component={IndexContainer}/>
Try adding the exact prop to all of your routes (except for your redirect), and you should properly get redirected to the home page with the correct URL.
More details on the exact prop here: React : difference between <Route exact path="/" /> and <Route path="/" />

react-router-dom refresh component when route changes

I used same component for different routes. When route changes, I want the component to be rendered.
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/hotels" component={HotelsPage} />
<Route path="/apartments" component={HotelsPage} />
</Switch>
When I change the route path from /hotels to /apartments, the component HotelsPage doesn't refresh.
What is the cool approach for this?
One of the ways you can get this sorted is by passing the props explicitly like :
<Route path="/hotels" component={props => <HotelsPage {...props} />} />
Firstly you can aggregate the Route into one like
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>
and secondly, your HotelsPage component is rendered both on /hotels, /apartments, it is similar case like path params, whereby the component doesn't mount again on path change, but updates thereby calling componentWillReceiveProps lifecycle function,
What you can do is implement componentWillReceiveProps like
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
console.log("here");
//take action here
}
}
DEMO
I guess just passing useLocation().pathname will resolve issue
useEffect(
() => {
// Your logics
});
}, [useLocation().pathname])

<Switch> component matching null value in react-router-4

I'm trying to migrate to use React Router 4 and having some trouble understanding the logic of the <Switch> component as it's used in the docs to handle a 404 (or unmatched) route.
For my entry JavaScript file, I have the following routes set up.
index.js
<Switch>
<Route path="/login" component={Login} />
<Route path="/forgot-password" component={ForgotPassword} />
<Route path="/email-verification" component={EmailVerification} />
<Route component={App} />
</Switch>
The Login component will check to see if the user is authenticated, and if so, redirect the user to the /dashboard route (via history.replace).
The App component is only accessible when the user is authenticated and it has a similar check to redirect the user to /login if she is not.
In my App component I have more specified routes that I can be sure are only accessible if the user is logged in.
App.js
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/accounts" component={Account} />
<Authorize permissions={['view-admin']}>
<Route path="/admin" component={Admin} />
</Authorize>
<Route path="/users" component={Users} />
<Route component={NotFound} />
</Switch>
Herein lies my problem. The Authorize component checks against the permissions passed to see if the user has those permissions, if so, it renders the children directly, if not, it returns null from render().
The expected behavior here is that the <Route path="/admin" /> does not render at all when there are insufficient permissions and the <Route component={NotFound} /> component renders.
According to the docs:
A renders the first child that matches. A
with no path always matches.
However, if I go to any route declared after the <Authorize> component, the router is matching to null. This means that, based on the example above, going to /users returns null. Is the expected behavior of react-router to return the first match in a <Switch/> component, even if it's a null value?
How can I provide a "catch-all" route (404) for such a situation without creating a <PrivateRoute> component for each of the many, authenticated routes in App.js? Should a null value really produce a match?
Unfortunately, react-router's Switch component won't work with routes nested inside other components like in your example. If you check the docs for Switch, it says:
All children of a <Switch> should be <Route> or <Redirect> elements.
... so your Authorize component is not actually legal there as a direct child of Switch.
If you have a read through the source code of the Switch component, you'll see that it rather evilly reads the props of each of its children and manually applies react-router's matchPath method on each child's path (or from) prop to determine which one should be rendered.
So, what's happening in your case is Switch iterates through its children until it gets to your Authorize component. It then looks at that component's props, finding neither a path or from prop, and calls matchPath on an undefined path. As you note yourself, "a <Route> with no path always matches", so matchPath returns true, and Switch renders your Authorize component (ignoring any subsequent Routes or Redirects, since it believes it found a match). The nested '/admin' route inside your Authorize component doesn't match the current path however, so you get a null result back from the render.
I'm facing a similar situation at work. My plan to work around it is to replace react-router's Switch in my routing code with a custom component which iterates through its children, manually rendering each one in turn, and returning the result of the first one that returns something other than null. I'll update this answer when I've given it a shot.
Edit: Well, that didn't work. I couldn't work out a supported way to manually invoke "render" on the children. Sorry I couldn't give you a workaround to Switch's limitations.
In case anyone reads this in >= 2019, one way to deal with this behaviour is to simply wrap the Route-component like so:
import React from 'react'
import { Route } from 'react-router-dom'
type Props = {
permissions: string[]
componentWhenNotAuthorized?: React.ElementType
}
const AuthorizedRoute: React.FunctionComponent<Props> = ({
permissions,
componentWhenNotAuthorized: ComponentWhenNotAuthorized,
...rest
}) => {
const isAuthorized = someFancyAuthorizationLogic(permissions)
return isAuthorized
? <Route {...rest} />
: ComponentWhenNotAuthorized
? <ComponentWhenNotAuthorized {...rest} />
: null
}
export default AuthorizedRoute
Then, simply use it as such:
import React from 'react'
import { Route, Switch } from 'react-router-dom'
import AuthorizedRoute from 'some/path/AuthorizedRoute'
import Account from 'some/path/Account'
import Admin from 'some/path/Admin'
import Dashboard from 'some/path/Dashboard'
import NotFound from 'some/path/NotFound'
import Users from 'some/path/Users'
const AppRouter: React.FunctionComponent = () => (
<Switch>
<Route
component={Account}
path='/accounts'
/>
<AuthorizedRoute
component={Admin}
componentWhenNotAuthorized={NotFound}
path='/admin'
permissions={['view-admin']}
/>
<Route
component={Dashboard}
path='/dashboard'
/>
<Route
component={Users}
path='/users'
/>
<Route
component={NotFound}
/>
</Switch>
)
export default AppRouter
Similar idea to what Robert said, here's how I did it
class NullComponent extends React.Component {
shouldComponentBeRenderedByRoute() {
return false;
}
render() {
return null;
}
}
class CustomSwitch extends React.Component {
render() {
return (
// React.Children.map returns components even for null, which
const children = React.Children.toArray(this.props.children).map(child => {
const { render, shouldComponentBeRenderedByRoute } = child.type.prototype;
if (shouldComponentBeRenderedByRoute && !shouldComponentBeRenderedByRoute.call(child)) {
return null;
}
if (shouldComponentBeRenderedByRoute) {
return render.call(child);
}
return child;
});
return <Switch>{children}</Switch>;
);
}
}
then use it just do
<CustomSwitch>
<Route path... />
<NullComponent />
<Route path... />
</CustomSwitch>
here, a component without shouldComponentBeRenderedByRoute function is assumed to be a valid Route component from react-router, but you can add more condition (maybe use path props) to check if it's a valid Route

Categories