The package _history_ 5.0.0, to create a custom history, does not work with the _Router_ component from _react-router-dom_ version 5.2.0. Instead use the history package version 4.9.0. It changes the address bar, but doesn鈥檛 render the component.
service/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
App.js
import React from 'react';
import { Router } from 'react-router-dom';
import Routes from './routes';
import customHistory from './services/history';
function App() {
return (
<Router history={customHistory}>
<Routes />
</Router>
);
}
export default App;
routes/index.js
import React from 'react';
import { Switch } from 'react-router-dom';
import Route from './Route';
import SignIn from '../pages/SignIn';
import SignUp from '../pages/SignUp';
import Dashboard from '../pages/Dashboard';
import Profile from '../pages/Profile';
export default function Routes() {
return (
<Switch>
<Route path="/" exact component={SignIn} />
<Route path="/register" component={SignUp} />
<Route path="/dashboard" component={Dashboard} isPrivate />
<Route path="/profile" component={Profile} isPrivate />
</Switch>
);
}
routes/Route.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
export default function RouteWrapper({
component: Component,
isPrivate,
...rest
}) {
const signed = true;
if (!signed && isPrivate) {
return <Redirect to="/" />;
}
if (signed && !isPrivate) {
return <Redirect to="/dashboard" />;
}
return <Route {...rest} component={Component} />;
}
RouteWrapper.propTypes = {
isPrivate: PropTypes.bool,
component: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
.isRequired,
};
RouteWrapper.defaultProps = {
isPrivate: false,
};
Don't know what your pages look like but took a guess. Created a codesandbox with working example of what I think you're asking. Will gladly help if this doesn't help figure out where the issue is coming from.
It was a statement. I don鈥檛 have any doubts about the code. I just put the code so you could understand the idea. But just to clarify, the idea is to redirect to signin when u try to access the private routes. I fixed downgrading the history package to the same version used on the react-router-dom package.
Most helpful comment
It was a statement. I don鈥檛 have any doubts about the code. I just put the code so you could understand the idea. But just to clarify, the idea is to redirect to signin when u try to access the private routes. I fixed downgrading the history package to the same version used on the react-router-dom package.