Home > Software design >  is it possible to show a Button only if admin use?
is it possible to show a Button only if admin use?

Time:01-07

I need some help or want to know if it is possible or not ..

I want to show a Button if only the current user has administrator rights.

In my redux state there is a isAdministrator Attribute and if the current user has isAdministrator: true then I want to show the Button.

return (
<div>
 {userInfo ? (
        <Link id="OpenUserManagament" to="/userManagement">
        <Button style={{ marginLeft: 10, marginBottom: 6 }} size="lg">
          User Management
        </Button>
      </Link>
        ):(
      <Nav.Link></Nav.Link>
        )}
</div>
)

So something after userInfo .. that´s my state Information

const userLogin = useSelector((state) => state.userLogin);
  const { userInfo } = userLogin;

{loading: true, userInfo: {…}}
loading: true
userInfo:
auth: {username: 'admin', password: '********'}
isAdministrator: true
token: {}
userID: "admin"
userName: "admin"
_id: ""
[[Prototype]]: Object
[[Prototype]]: Object

CodePudding user response:

What you are asking is possible. But from your code, I can't understand how your userLogin object looks like. You can try to console.log it, so you can see what is in it.

once you solve there you need to wrap your code inside a div like this:

//here is component body

return (
    <div>
        {userInfo.userId === "admin" ?? (
        <Link id="OpenUserManagament" to="/userManagement">
        <Button style={{ marginLeft: 10, marginBottom: 6 }} size="lg">
          User Management
        </Button>
      </Link>
        )}
    </div>

) 

It should work if you can sortout userInfo

CodePudding user response:

A simple ternary does the trick...

// Just a dummy example...
function AdminButton({ userInfo }) {
  return (
    <div>
      {userInfo.isAdministrator ? (
        <React.Fragment>
          <p>hello admin here&apos;s some links and blah blah blah</p>
          <button onClick={() => alert('yay!!')}>Hello, admin!</button>
        </React.Fragment>
      ) : null}
    </div>
  );
}

ReactDOM.render(<AdminButton userInfo={{ isAdministrator: true }} />, root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<h1>Welcome! If you see a button below, you are the admin</h1>
<div id="root"></div>

I just used null, which displays nothing if the user isn't a admin for the purpose of the demo. You can display other stuff with something like:

(/* ... */) : (
  <Nav.Link></Nav.Link>
)
  •  Tags:  
  • Related