'How to create an admin route and another private route for registered users with a normal route?
I have used this code as the private route, but I want a another separate route only for admins. How can I change the code?
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import {connect } from 'react-redux'
import PropTypes from 'prop-types'
const Private = ({ component: Component,
auth:{loading, isAuthenticted},
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticted && loading ?
(<Redirect to='/signin'/>
):(
<Component {...props}/>)
}
/> );
Private.propTypes={
auth:PropTypes.object.isRequired,
}
const mapStateToProps=state=>({
auth:state.auth
})
export default connect(mapStateToProps)(Private);
Solution 1:[1]
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import {connect } from 'react-redux'
import PropTypes from 'prop-types'
import Spinner from '../layouts/Spinner';
const Admin = ({ component: Component,
auth:{loading, isAuthenticated,user},
...rest
}) => (
<Route
{...rest}
render={props =>
loading ? (
<Spinner />
) : isAuthenticated ? (
(user.userRole=='Admin')?
<Component {...props} />:( <Redirect to="/index" />)
) : (
<Redirect to="/signin" />
)
}
/> );
Admin.propTypes={
auth:PropTypes.object.isRequired,
}
const mapStateToProps=state=>({
auth:state.auth
})
export default connect(mapStateToProps)(Admin);
I added user Role field which is already in my state.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hasitha Kumarasinghe |