Reputation: 2827
I'm building a ReactJS application (my first) and i need to hide some part of my pages due to authorization.
For example i have a menu on left and some li
should be under authorization.
Right now i didnt find some API for this purpose, just something for "Login".
For example:
<ul>
<authorization hasRole="simple_user">
<li>Read Post</li>
</authorization>
<authorization hasRole="registerd_user">
<li>Create Post</li>
</authorization>
<authorization hasRole="admin_user">
<li>Delete Post</li>
</authorization>
</ul>
Upvotes: 0
Views: 1570
Reputation: 7973
You can use switch
statement.
class HideMe extends React.Component {
constructor(){
super();
this.state = {
isAuthorized: false,
role: ''
};
this.checkAuto = this.checkAuto.bind(this);
this.autorization = this.autorization.bind(this);
}
checkAuto(e){
// of course you should send some request to the server
// and i just simulate it : "admin", "user", "SEO"
console.log(e.target.value)
switch(e.target.value) {
case 'admin':
this.setState({isAuthorized: true, role: 'admin'});
break;
case 'user':
this.setState({isAuthorized: true, role: 'user'});
break;
case 'SEO':
this.setState({isAuthorized: true, role: 'SEO'});
break;
default:
this.setState({isAuthorized: false, role: ''});
break;
}
}
autorization(){
console.log(this.state.isAuthorized, this.state.role)
if (this.state.isAuthorized && this.state.role === "admin")
return <div className="admin">This is Admin</div>
if (this.state.isAuthorized && this.state.role === "SEO")
return <div className="seo">This is SEO</div>
if (this.state.isAuthorized && this.state.role === "user")
return <div className="user">This is user</div>
else
return <div className="notuser">not Authorized</div>
}
render(){
return <div>
<label>Simulate autorization: <input type="text" onChange={this.checkAuto}/> </label>
<hr/>
{this.autorization()}
</div>
}
}
React.render(<HideMe />, document.getElementById('container'));
fiddle example. I hope it will help you.
Thanks
Upvotes: 2
Reputation: 3297
The authorization component can be as below
<ul><authorization role="simple_user" /></ul>
It can be returned as follows
////////////
return (
<div>
{(() => {
switch (this.props.role){
case "simple_user":
return <li>Read Post</li>;
case "registered_user":
return <li>Create Post</li>;
case "admin_user":
return <li>Delete Post</li>;
default:
return <li>Read Post</li>;
}
})()}
</div>
);
Upvotes: 0