skip to Main Content

I want to render buttons only if the isAdmin that i get from the local storage and save in a variable is true, if isAdmin is false, i only want to render the Cancel button.

The Buttons are part of a form

But it shows me all three buttons no matter what.

These are the options i tried:

Version 1

       {console.log("Value of is admin:" + isAdmin)}
{isAdmin 
       ?
  
        <div>
          <button className="update-button" id="update_button" onClick={handleUpdate}>Update</button>
          <button className="delete-button" id="delete-button" onClick={handleDelete} >Delete</button>
          <button className="cancel-button" id="cancel-button" onClick={handleCancel} >Cancel</button>
        </div>

        : <button className="cancel-button" id="cancel-button" onClick={handleCancel} >Cancel</button>
      }
        </form>
      )

Version 2

{isAdmin && (
  
        <div>
          <button className="update-button" id="update_button" onClick={handleUpdate}>Update</button>
          <button className="delete-button" id="delete-button" onClick={handleDelete} >Delete</button>
        </div>
      )}

      <button className="cancel-button" id="cancel-button" onClick={handleCancel} >Cancel</button>
    
        </form>
        ```

2

Answers


  1. I Believe your variable isAdmin isn’t a boolean, if so, the condition is just saying, yes it does exist, and renders

    try logging

    typeof(isAdmin) 
    

    to see

    sometimes when you set the variable to localstorage it stringify it, so you need do to JSON.parse(isAdmin)

    Login or Signup to reply.
  2.     <div>
    {isAdmin &&
       <>
              <button className="update-button" id="update_button" onClick={handleUpdate}>Update</button>
              <button className="delete-button" id="delete-button" onClick={handleDelete} >Delete</button>
       </>}
      <button className="cancel-button" id="cancel-button" onClick={handleCancel} >Cancel</button>
      </div>   
      </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search