Reputation: 1132
I want to make some routes private for admin access.
Where on successful login admin can able to access the path.
But here i am facing problem on login it is redirecting to error page
.
Any thing else I need to do here to make this route private? Any suggestion. Thanks in advance.
//main.js
import React, { Component } from 'react';
import {Switch, Route} from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Homepage from './user/Homepage';
import Aboutme from './user/AboutMe';
import Error from './user/Error';
import Dashboard from './admin/Dashboard';
class Main extends Component {
static propTypes = {
auth: PropTypes.object.isRequired
}
render(){
const { isAuthenticated, user } = this.props.auth;
return(
<Switch>
<Route exact path="/" component={Homepage}/>
<Route path="/about" component={Aboutme}/>
<Route component={Error}/>
{ user ? (user.is_admin === true && isAuthenticated ?
( <Route path="/dashboard" component={Dashboard}/> ) : ( <Route component={Error}/>) ): <Route component={Error}/> }
</Switch>
)
}
}
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps, null)(Main);
Upvotes: 0
Views: 53
Reputation: 730
That is because you have
<Route component={Error}/>
as the third item of switch.
Switch renders the first child or that matches the location.
Since you have no path specified, i guess it will always match, and the Switch
won't use the later parts routes.
As a solution, either use this with a path where you redirect, or remove completely.
If you're interested in a different solution for private routes, check this article for example: https://tylermcginnis.com/react-router-protected-routes-authentication/
Upvotes: 1