Paweł Baca
Paweł Baca

Reputation: 888

React application with users roles

I started working with React/Redux about 2 months ago and I want to make an application with user roles. When a user logs in I want to change my Route component:

<Route path={"/"} component={MainPage}></Route>

To component

<Route path={"/"} component={MainPageUser}></Route>

If admin

<Route path={"/"} component={MainPageAdmin}></Route>

But if I make a switch with my Router I get the error

Warning: [react-router] You cannot change <Router routes>; it will be ignored

I want make access based on the type of account.

Upvotes: 2

Views: 3481

Answers (2)

Brett DeWoody
Brett DeWoody

Reputation: 62851

One option is to create a single component for the / path, and within that component return a different component based on the user role.

<Route path={"/"} component={Home} userRole={userRole}></Route>

class Home extends React.Component {
  render() {
    return this.props.userRole === "admin" ? <HomeAdmin /> : <HomeVisitor />;
  }
}

Upvotes: 5

Lee이민규
Lee이민규

Reputation: 213

I recommend you rootPageComponent wrapping the switchs.

How about this?

(Below is a just simple sample code. Please note that it does not work correctly)

<Route path={"/"} component={RootPage}></Route>

// RootPage.js
export default const RootPage({role}) => {
    switch(role) {
        case USER: return <MainPageUser />
        case ADMIN: return <AdminPage />
        default: return <MainPage />
    }
}

Upvotes: 3

Related Questions