I want to do something like:
<Route>
<MyComponent someCondition={true/false}>
<Route1 />
....
</MyComponent>
</Route
To handle some conditional rendering. However, <MyComponent /> seems not mounted upon rendering.
My question is: can we include normal react component within <Route>? If not, is there a better way to handle conditional routing?
What exactly do you mean by conditional routing? Assuming you mean something like not letting a user hit a route if they aren't authenticated, you can use react-router's onEnter hooks . You can make a parent <Route> that doesn't have a component prop and just handles routing checks. I used some simple onEnter checks in this example.
// onEnter hooks for login and home page to redirect if necessary
const checkAuth = function (nextState, replace) {
const { user } = store.getState()
if (isEmpty(user)) {
replace('/')
}
}
const checkSkipAuth = function (nextState, replace) {
const { user } = store.getState()
if (!isEmpty(user)) {
replace('/home')
}
}
var Index = () => {
return (
<Provider store={store}>
<Router history={history}>
<Route path='/' component={Container}>
<IndexRoute component={Login} onEnter={checkSkipAuth} />
<Route path='home' component={Home} onEnter={checkAuth} />
<Route path='*' component={NoMatch} />
</Route>
</Router>
</Provider>
)
}
Related
So recently I found out two ways of creating private routes in react.
With a HOC (higher-order component):
const PrivateRoute = ({ user, children }) => {
if (!user) {
return <Navigate to="/home" replace />;
}
return children;
};
const App = () => {
...
return (
<>
...
<Routes>
<Route path="/home" element={<Home />} />
<Route
path="/privateroute"
element={
<PrivateRoute user={user}>
<PrivateComponent />
</PrivateRoute >
}
/>
...
</Routes>
</>
);
};
With substituting routes completely
const App = () => {
...
return (
<>
{user ? (
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/privateroute" element={<PrivateComponent />} />
...
</Routes>
) : (
<Routes>
<Route path="/home" element={<Home />} />
...
</Routes>
)}
</>
);
}
My fellow colleague told me that the second way is quite bad since it completely erases some routes (if user is falsy then there is no route to /privateroute). But on my question why might that be bad he had no definitive answer. I couldn't find anything on the internet either. Any thoughts on which way is the best?
Between these two options, the first is the preferred solution since it keeps all routes mounted so they there will be no race condition between setting the user state and issuing an imperative navigation action to one of the protected routes. In other words, with the second implementation you have to wait for the user state to update and trigger a component rerender so the protected routes are mounted and available to be navigated to.
The second method also duplicates unauthenticated routes if it's all one or the other. Code duplication should be avoided.
Note however though that the first example isn't a Higher Order Component, it's just a wrapper component.
Note also that it's more common to create a PrivateRoute component as a Layout Route instead of as a Wrapper component. The change is trivial but it makes the component a little more wieldy. Render an Outlet component for nested routes instead of the children prop for a single wrapped child component.
import { ..., Outlet } from 'react-router-dom';
const PrivateRoute = ({ user }) => {
return user ? <Outlet /> : <Navigate to="/home" replace />;
};
Now instead of wrapping each individual route you want to protect you render a layout route that wraps an entire group of routes you want to protect. It makes your code more DRY.
const App = () => {
...
return (
<>
...
<Routes>
<Route path="/home" element={<Home />} />
... other unprotected routes ...
<Route element={<PrivateRoute />}>
<Route path="/privateroute" element={<PrivateComponent />} />
... other protected routes ...
</Route>
... other unprotected routes ...
</Routes>
</>
);
};
I have a component that I am using in React Router v6 for managing private routes, that does some checks on an auth token, and will either render the Outlet component or will redirect to a login page.
I have -
import { Outlet } from 'react-router-dom';
export const CheckAuth = (props) => {
const valid = ...;
if (!valid) {
window.location.replace(loginUrl);
return null;
}
return <Outlet />;
};
and using it like -
<Route element={<CheckAuth token={authToken} />}>
// ... private routes ...
</Route>
I can mock out window.location.replace with Jest
delete window.location;
window.location = { replace: jest.fn() };
...
render(<CheckAuth token={token} />)
expect(window.location.replace).toHaveBeenCalledWith(loginUrl);
but how can I test the Outlet component using Testing Library?
If it helps anyone, I ended up just wrapping the components in the test with a react router components, and passed a dummy component as a child to Route and asserted that some fake text in that component was or was not rendered
Outside the test block -
const FakeComponent = () => <div>fake text</div>;
and for a failure scenario, where the outlet should not render -
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route element={<CheckAuth />}>
<Route path="/" element={<FakeComponent />} />
</Route>
</Routes>
</MemoryRouter>
);
expect(screen.queryByText('fake text')).not.toBeInTheDocument();
and for a success scenario, assert that the text is present -
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route element={<CheckAuth token={correctToken}/>}>
<Route path="/" element={<FakeComponent />} />
</Route>
</Routes>
</MemoryRouter>
);
expect(screen.queryByText('fake text')).toBeInTheDocument();
I know this issue has been discussed before. But, somehow I cannot get it work in my application.
Normally, the navigation works fine between components. However, history.push only changes the url but does not update the content. For example, in the Login page, I want to navigate user to Home page if already logged in. But, the code only updates the url. Any ideas?
const Login = () => {
useEffect(() => {
if (authenticationService.currentUserValue != null) {
history.push('/home');
}
}, [])
//other code
}
In index.js, I have the following
<BrowserRouter basename={baseUrl} history={history}>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter >,
In app.js, I have:
<Layout>
<Switch>
<PrivateRoute exact path="/home" component={withRouter(Home)} />
<Route exact path='/home' component={withRouter(Home)} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={withRouter(Register)} />
</Switch>
</Layout>
The issue in your case is that you are using a custom history with BrowserRouter which isn't correct. BrowserRouter uses its own history and you must use that to change pages
const Login = ({history}) => {
useEffect(() => {
if (authenticationService.currentUserValue != null) {
history.push('/home');
}
}, [])
//other code
}
If you have used custom history for a reason, then you need to use Router with a custom history prop
<Router basename={baseUrl} history={history}>
<Provider store={store}>
<App />
</Provider>
</Router >
I have a file with router and a component. Shortly, the code is like this:
// define the routes for each language ..
const InnerRoutes = (
<Route>
<IndexRoute page="home" component={StaticPage}></IndexRoute>
<Route path="contacts" component={ContactsPage}></Route>
<Route path="(:page)" component={StaticPage}></Route>
</Route>
);
// define the routes for all the languages, using InnerRoutes ..
const AllRoutes = (
<Router history={browserHistory}>
<Route path='/' component={App} language="bg">
{InnerRoutes}
<Route path="en" language="en">
{InnerRoutes}
</Route>
</Route>
</Router>
);
// and render our app ..
ReactDOM.render(
AllRoutes,
document.getElementById('app')
);
My question is: how can I have the App component state changed when router change is triggered?
And of course - have the router params in the app state.
(Because currently I can take the router stuff from the App component's method componentDidUpdate and then trigger setState to change the App state. Unfortunately - then I have the componentDidUpdate triggered twice.)
I've added this to my App and it seems to receive changes when routes change. More reference here
class App extends React.Component {
...
getInitialState() {
return {
lang: 'en' // default
};
}
componentWillReceiveProps(props) {
console.log('location: ', props.location.pathname);
var newLang = props.location.pathname.split('/').shift();
if(this.state.lang !== newLang) {
this.setState({lang: newLang});
}
}
render() {
const lang = this.state.lang;
return (
<AboutPage language={lang} />
<Support language={lang} />
);
}
}
If this doesn't work, you can also look into how two components talk to each other
I don't really get how to constrain params with, for example a regex.
How to differentiate these two routes?
<Router>
<Route path="/:alpha_index" component={Child1} />
<Route path="/:numeric_index" component={Child2} />
</Router>
And prevent "/123" from firing the first route?
React-router v4 now allows you to use regexes to match params -- https://reacttraining.com/react-router/web/api/Route/path-string
const NumberRoute = () => <div>Number Route</div>;
const StringRoute = () => <div>String Route</div>;
<Router>
<Switch>
<Route exact path="/foo/:id(\\d+)" component={NumberRoute}/>
<Route exact path="/foo/:path(\\w+)" component={StringRoute}/>
</Switch>
</Router>
More info:
https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-match-parameters
I'm not sure if this is possible with React router at the moment. However there's a simple solution to your problem. Just do the int/alpha check in another component, like this:
<Router>
<Route path="/:index" component={Child0} />
</Router>
const Child0 = (props) => {
let n = props.params.index;
if (!isNumeric(n)) {
return <Child1 />;
} else {
return <Child2 />;
}
}
* Note that the code above does not run, it's just there to show what I mean.