1

I want to implement role based authorization using render props. I have three user types and I want to give each user type access to different parts of the nav bar and different pages in my application.

I am not sure how to implement it, any suggestions? I tried using a HOC but that didn't work out for me.

lshawa
  • 45
  • 9
  • I suppose you have to save in the state of redux a value of userType or something. Make an action creator that checks the type of the user, either with an api call or checking the properties of the user object. Then use a mapStateToProps to bind the userType redux state to a prop in you component, and use conditionals to check what type of user is logged. – Paul Miranda Jul 04 '19 at 23:38
  • How are you obtaining the user types? – Paul Miranda Jul 04 '19 at 23:40

1 Answers1

2

Here is one way of doing it,

assuming that user is stored in local storage (or you can save it in the state of redux),

var user = localStorage.getItem('user')
if (user) {
   user = JSON.parse(user)
}

inside return() :

            <Switch>
                {/*any user*/}
                <Route exact path='/' component={Home}/>
                <Route exact path='/home' component={Home}/>
                <Route exact path='/about' component={About}/>
                <Route exact path='/contact' component={Contact}/>
                <Route exact path='/register' component={Register}/>

                {/*admin*/}
                {user && user.role === "ADMIN" &&
                <>                  
                    <Route path='...' component={...}/>
                    <Route path='...' component={...}/>
                    <Route path='...' component={...}/>
                </>

                {/*user*/}
                {user && user.role === "USER" &&
                <>                  
                    <Route path='...' component={...}/>
                    <Route path='...' component={...}/>
                    <Route path='...' component={...}/>
                </>

                <Route component={NotFoundPage}/>
            </Switch>
Tenusha Guruge
  • 2,147
  • 3
  • 18
  • 38