Answer the question
In order to leave comments, you need to log in
How to fix history of undefined error when using BrowserRouter from react-router-dom version 5 module?
Why is there an error when using BrowserRouter from react-router-dom version 5
Uncaught TypeError: Cannot read property 'history' of undefined
import "../../styles/scss/app.scss";
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import PrivateRoute from 'react-private-route';
import Login from './Login';
import Home from './Home';
import NotFound from "./NotFound";
export default class App extends React.Component {
render() {
return(
<BrowserRouter>
<Switch>
<Route path="/login" component={Login} />
<PrivateRoute exact path="/" component={Home} isAuthenticated={true} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)
}
}
import React, {Suspense} from "react";
import ReactDOM from "react-dom";
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
import App from "./components/App";
ReactDOM.render(
<I18nextProvider i18n={i18n}>
<Suspense fallback="Loading">
<App />
</Suspense>
</I18nextProvider>,
document.getElementById('root')
);
Answer the question
In order to leave comments, you need to log in
Cut out react-private-route. This library uses the previous version of react-router.
The component you need can be implemented like this:
const PrivateRoute = ({ component: Component, render, isSignedIn, ...rest }) => (
<Route
{...rest}
render={props => {
if (!isSignedIn) return (
<Redirect
to={{
pathname: '/login',
state: { referrer: props.history.location.pathname },
}}
/>
);
if (render) return render({ ...props });
return <Component {...props} />;
}}
/>
);
const mapStateToProps = (state) => ({
isSignedIn: isSignedInSelector(state),
});
export default connect(mapStateToProps)(PrivateRoute);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question