I'm looking for a way to do some route protection with react-router-4. Looking at an example in the documentation, they create a Component which is rendered like this:
<PrivateRoute path="/protected" component={Protected} />
and the privateRoute component:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
I don't really understand why I should want to pass the "Protected" component as a property and then have to take care of spreading all the ...props and ...rest.
Before I was reading this doc (and other example), I created the following code, which just nest the routes in another component which takes care of the authentication part.
Because my example (which seems to work perfectly well), looks way more simplistic, I must be missing something.
Are there any downsides on this approach?
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import Nav from './Nav';
// dummy
const Auth = {
isAuthenticated: () => { return true; }
}
const Home = () => <h1>Home</h1>
const SignIn = () => <h1>SignIn</h1>
const About = () => <h1>About</h1>
class PrivateOne extends Component {
render() {
console.log(this.props);
return <h1>Private</h1>
}
}
const PrivateTwo = () => <h1>PrivateTwo</h1>
const PrivateThree = () => <h1>PrivateThree</h1>
const NotFound = () => <h1>404</h1>
const Private = ({isAuthenticated, children}) => {
return(
isAuthenticated ? (
<div>
<h1>Private</h1>
{children}
</div>
) : (
<Redirect to={{
pathname: '/sign_in',
}}/>
)
)
}
const App = () =>
<div>
<Router>
<div>
<Nav />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/sign_in" component={SignIn} />
<Private isAuthenticated={Auth.isAuthenticated()}> {/* or some state later on */}
<Route path="/private1" component={PrivateOne} />
<Route path="/private2" component={PrivateTwo} />
<Route path="/private3" component={PrivateThree} />
</Private>
<Route component={NotFound} />
</Switch>
</div>
</Router>
</div>
export default App;
Related
i using react-router for my project,
in that there's a problem which is for every route "#" sign is added at the start of every router path..
ex": http://localhost:3000/#/login
i want to remove that # sign but i couldn't able solve it my self.
procedure of my routing is
in app.js im checking the user is signed in or not if not signed in then he will redirect into /login page.(for that also it is showing path as http://localhost:3000/#/login)
below is the app.js
import React, { Component, Fragment } from "react";
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
// import { renderRoutes } from 'react-router-config';
import "./App.scss";
import { connect } from "react-redux";
import { loadUser } from "./actions/authActions";
const loading = () => (
<div className="animated fadeIn pt-3 text-center">Loading....</div>
);
// Containers
const DefaultLayout = React.lazy(() =>
import("./containers/DefaultLayout/DefaultLayout")
);
// Pages
const Login = React.lazy(() => import("./views/Login/Login"));
const Register = React.lazy(() => import("./views/Register/Register"));
const Page404 = React.lazy(() => import("./views/Page404/Page404"));
const Page500 = React.lazy(() => import("./views/Page500/Page500"));
class App extends Component {
componentDidMount() {
this.props.LOADUSER();
}
render() {
return (
<HashRouter>
<React.Suspense fallback={loading()}>
<Switch>
{!this.props.isAuthenicated ? (
<Fragment>
<Redirect from="*" to="/login" />
<Route
exact
path="/login"
name="Login Page"
render={props => <Login {...props} />}
/>
{/* <Route
exact
path="/register"
name="Register Page"
render={(props) => <Register {...props} />}
/>
<Route
exact
path="/404"
name="Page 404"
render={(props) => <Page404 {...props} />}
/>
<Route
exact
path="/500"
name="Page 500"
render={(props) => <Page500 {...props} />}
/> */}
</Fragment>
) : (
<Route
name="Home"
path="/"
render={props => <DefaultLayout {...props} />}
/>
)}
</Switch>
</React.Suspense>
</HashRouter>
);
}
}
const mapStateToProps = state => ({
isAuthenicated: state.auth.isAuthenicated,
isLoading: state.auth.isLoading,
error: state.error,
token: state.auth.token
});
const mapDispachToProps = dispach => {
return {
//LOGIN: (newUser) => dispach(login(newUser)),
LOADUSER: () => dispach(loadUser())
};
};
export default connect(mapStateToProps, mapDispachToProps)(App);
else he is signed in then im using a component called DefaultLayout Component I will render it.
it has all the routes for other usages which is using routes from routes.js.
below is the DefaultLayout Component
import React, { Component, Suspense } from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import * as router from "react-router-dom";
import { Container } from "reactstrap";
import { logout } from "../../actions/authActions";
import { ToastContainer } from "react-toastify";
import Loader from "react-loaders";
import "react-toastify/dist/ReactToastify.css";
import {
AppHeader,
AppSidebar,
AppSidebarFooter,
AppSidebarForm,
AppSidebarHeader,
AppSidebarMinimizer,
AppBreadcrumb2 as AppBreadcrumb,
AppSidebarNav2 as AppSidebarNav
} from "#coreui/react";
// sidebar nav config
import _navs from "../../_nav";
// routes config
import routes from "../../routes";
import { connect } from "react-redux";
const DefaultHeader = React.lazy(() => import("./DefaultHeader"));
class DefaultLayout extends Component {
state = {
isAuthenicated: true
};
loading = () => <Loader type="ball-triangle-path" />;
signOut(e) {
e.preventDefault();
this.props.history.push("/login");
this.props.LOGOUT();
}
render() {
return (
<div className="app">
<AppHeader fixed>
<Suspense fallback={this.loading()}>
<DefaultHeader onLogout={e => this.signOut(e)} />
</Suspense>
</AppHeader>
<div className="app-body">
<AppSidebar fixed display="lg">
<AppSidebarHeader />
<AppSidebarForm />
<Suspense>
<AppSidebarNav
navConfig={_navs}
{...this.props}
router={router}
/>
</Suspense>
<AppSidebarFooter />
<AppSidebarMinimizer />
</AppSidebar>
<main className="main">
<AppBreadcrumb appRoutes={routes} router={router} />
<Container fluid>
<Suspense fallback={this.loading()}>
<Switch>
{routes.map((route, idx) => {
return route.component ? (
<Route
key={idx}
path={route.path}
exact={route.exact}
name={route.name}
render={props => (
<route.component {...props} {...route.props} />
)}
/>
) : null;
// (
// <Redirect from="*" to="/dashboard" />
// );
})}
<Redirect from="*" to="/" />
</Switch>
</Suspense>
<ToastContainer autoClose={3000} position="bottom-center" />
</Container>
</main>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
isAuthenicated: state.auth.isAuthenicated,
error: state.error
});
const mapDispachToProps = dispach => {
return {
LOGOUT: () => dispach(logout())
};
};
export default connect(mapStateToProps, mapDispachToProps)(DefaultLayout);
example of routes.js also below
const routes =[{
path: "/",
exact: true,
name: "Home",
component: Dashboard
},
{
path: "/user_overview",
name: "Users Overview",
component: Register
}]
for every route it's showing # can anyone help me to resolve that # sign in the route path?
Thank you!
You are using HashRouter this is the purpose of this Router.
Usually one uses it in-order to prevent the server to get those routes.
If you want to use real routes just replace it with BrowserRouter.
Pay attention that your server will need to be able to support those routes.
navigate to some route say /some/page press reload, make sure that your server return your client code.
Given an authentication token and a function checkToken how would I go about rerouting from multiple routes using the react router to prevent repetition like the below?
<Route exact path="/" render={() => {
return checkToken() ? (<Dashboard />) : (<Redirect to="/login" />)
}} />
<Route exact path="/about" render={() => {
return checkToken() ? (<About />) : (<Redirect to="/login" />)
}} />
It gets cumbersome if I have a couple dozen routes to have this repeated.
Surely there must be a better way!
Here is how I like to handle this:
Create a routers folder in src
Inside the router folder create 3 files AppRouter.js, PrivateRoute.js & PublicRoute.js
Here is your PublicRoute.js:
import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
export const PublicRoute = ({ isAuthenticated, component: Component, ...rest }) => (
<Route {...rest} component={(props) => (
isAuthenticated ? <Redirect to="/dashboard" /> : <Component {...props} />
)} />
);
const mapStateToProps = state => ({
isAuthenticated: // however you need to keep track of that...
});
export default connect(mapStateToProps)(PublicRoute);
Here is your PrivateRoute.js:
import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ isAuthenticated, component: Component, ...rest }) => (
<Route {...rest} component={(props) => (
isAuthenticated ? <Component {...props} /> : <Redirect to="/" />
)} />
);
const mapStateToProps = state => ({
isAuthenticated: // however you need to keep track of that...
});
export default connect(mapStateToProps)(PrivateRoute);
And finally here is your AppRouter.js:
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Dashboard from '../components/Dashboard';
import NotFound from '../components/NotFound';
import Login from '../components/Login';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';
const AppRouter = () => (
<BrowserRouter>
<Switch>
{/* use PublicRoute for public routes */}
<PublicRoute exact path="/" component={Login} />
{/* use PrivateRoute for private routes */}
<PrivateRoute path="/dashboard" component={Dashboard} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
);
export default AppRouter;
For more info on HOCs (Higher Order Components) look up the docs: https://reactjs.org/docs/higher-order-components.html
One way to achieve it is by placing your checkToken function inside componentDidMount so you will always check if your user is authenticated each time this component is mounted.
After that you can do something like this:
let routes = (
<Switch>
<Route path="/login" component={LoginComponent} />
<Redirect to="/" />
</Switch>
);
if (isAuth) {
routes = (
<Switch>
<Route path="/yourRoute" component={YourComponent} />
<Redirect to="/" />
</Switch>
);
}
return (
<div>
{routes}
</div>
I have a simple route.js file
const PrivateRoute = ({ component, ...rest }) => {
const isAuthed = localStorage.getItem('Authorization')
return (
<Route {...rest} exact
render = {(props) => (
isAuthed ? (
<div>
{React.createElement(component, props)}
</div>
) :
(
<Redirect
to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
)}
/>
)
}
class App extends Component {
componentWillMount() {
if (localStorage.getItem('Authorization')) {
history.push(`${history.location.pathname}`)
}
}
render() {
return (
<Router history={history}>
<div className="App-pageContainer">
<Route exact path="/" render={() => <Redirect to="/login" />} />
<Route path={'/login'} component={Login} />
<PrivateRoute path={'/dashboard'} component={Dashboard} />
</div>
</Router>
)
}
}
export default App
What I need is to put condition if the user has a key in localStorage(Authentication) then I want to redirect it to /dashboard if it doesn't contain Authentication in localStorage then I want to redirect it to /login.
I am totally stuck with this from past few days. Please help!!!
I think this kind of questions is too broad for an answer.
However, you could follow this amazing post to be able to implement that functionality.
Protected routes and authentication with React Router v4
This is what you got after finishing
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom'
const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 100)
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 100)
}
}
const Public = () => <h3>Public</h3>
const Protected = () => <h3>Protected</h3>
class Login extends React.Component {
render() {
return (
<div>
Login
</div>
)
}
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
fakeAuth.isAuthenticated === true
? <Component {...props} />
: <Redirect to='/login' />
)} />
)
export default function AuthExample () {
return (
<Router>
<div>
<ul>
<li><Link to="/public">Public Page</Link></li>
<li><Link to="/protected">Protected Page</Link></li>
</ul>
<Route path="/public" component={Public}/>
<Route path="/login" component={Login}/>
<PrivateRoute path='/protected' component={Protected} />
</div>
</Router>
)
}
I'm using react router v4 with redux and i want to make use of private and protected route to redirect if user is not logged in.
i have this Routes component:
class Routes extends Component {
render() {
const { auth } = this.props;
// so checks against isAuthenticated can pass
if (auth.isAuthenticated !== undefined) {
return (
<div>
<Route exact component={() => <Home />} />
<PublicRoute
authed={() => auth.isAuthenticated}
path="/login"
component={(routerProps) => <Login {...routerProps} />}
/>
<PublicRoute
authed={() => auth.isAuthenticated}
path="/register"
component={(routerProps) => <Register {...routerProps} />}
/>
<PrivateRoute
authed={() => auth.isAuthenticated}
path="/dashboard"
component={Dashboard}
/>
</div>
);
} else {
return <div></div>
}
}
}
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default withRouter(connect(mapStateToProps)(Routes));
it is implemented like this:
class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
store.dispatch(checkAuth());
}
render() {
return (
<Provider store={store}>
<Router>
<Theme>
<Routes />
</Theme>
</Router>
</Provider>
);
}
}
This is the PrivateRoute:
export function PrivateRoute({ component: Component, authed, ...rest }) {
const isAuthenticated = authed();
return (
<Route
{...rest}
render={props =>
isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}
What is the best way to pass that auth prop, is it ok if i connect the Routes component and pass the auth from there, or should i be passed from somewhere else, maybe connect each component that needs it and read from there? Also how would this approach play with nested routes, like /dashboard/settings? Thanks
Actually, it is ok to use this type of private route in react, but you should check two moments:
I should check, that you do not have exact attribute, so all your routes like /dashboard/panel1, /dashboard/panel2 will be private to
auth.isAuthenticated}
path="/dashboard"
component={Dashboard}
/>
You will have some problem with connect. There is a simple fix for that:
export default connect(mapStateToProps, null, null, {
pure: false,
})(PrivateRoute);
more information here:
React router private routes / redirect not working
I am using react router v4 and I'm trying to wrap my head around a react-router / redux / HOC related issue. I have a higher order component working. The HOC itself is connect()-ed to redux store. This approach works perfectly if I wire it up in a <Route /> via a component prop: <Route path="/profile" component={ withAuth(Profile) } /> does work.
However, when I try to do the same with a <Route /> and a render prop it does not work: <Route path="/profile" render={ () => withAuth(Profile) } /> The console throws "Route.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object." It does work when I omit the HOC: <Route path="/profile" render={ () => <Profile /> } /> so I suspect a problem with the HOC but I can't find it.
The reason I'm trying to use render is I'd like to pass additional props to the HOC. Besides it bugs me that I can't find the bug.
Can anybody with a fresh eye have a look and put me on the right path? Thanks!
/* === app.js === */
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import Header from './header';
import Home from './home';
import Content from './about';
import Profile from './profile';
import withAuth from './withAuth';
import store from '../reducers/store';
export default class App extends Component {
render() {
return (
<Provider store={store}>
<div className="mdl-grid">
<Header />
<main className="mdl-layout__content">
<div className="page-content">
<Route path="/" exact component={Home} />
<Route path="/about" component={Content} />
<Route path="/profile" render={ () => withAuth(Profile) } />
</div>
</main>
</div>
</Provider>
)
}
}
/* === withAuth.js (Higher order component) === */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
const HOC = WrappedComponent => {
return class extends Component {
render() {
if (this.props.auth) {
return <WrappedComponent authenticated={this.props.auth} {...this.props} />
} else {
return <Redirect to="/" />
}
}
}
}
function mapStateToProps({ auth }) {
return { auth };
}
export default WrappedComponent => connect(mapStateToProps)( HOC(WrappedComponent) );
The reason it doesn't work is because, here
<Route path="/profile" render={ () => withAuth(Profile) } />
render is actually assigned a function withAuth and not the returned value. What you need to do is
const AuthProfile = withAuth(Profile);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<div className="mdl-grid">
<Header />
<main className="mdl-layout__content">
<div className="page-content">
<Route path="/" exact component={Home} />
<Route path="/about" component={Content} />
<Route path="/profile" render={ (props) => <AuthProfile {...props}/> } />
</div>
</main>
</div>
</Provider>
)
}
}
The difference between
render={ () => withAuth(Profile) }
and
render={ (props) => <AuthProfile {...props}/> }
is that in the first case its an arrow function that is bound to the context. Whereas in the second case its a function returning a component
I think your problem is with the way you use <Redirect />, you have to put it in <Route />. Look at this example:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)