2

I am Working on SPFx and writing below code to get current user belong to particular group or not and if its belong then show else hide

below is my interface:

UserInGroup:boolean;

State:

UserInGroup:false

and method to get current user belong to particular group or not calling this on component did mount:

checkMemberGroups() {
    var absoluteUri = _spPageContextInfo.webAbsoluteUrl;
    var reactHandler = this;
    var UserGroup = "Admin"
    $.ajax({
            async: false,
            headers: {
                "accept": "application/json; odata=verbose"
            },
            method: "GET",
            url: absoluteUri + "/_api/Web/CurrentUser/Groups",

                success: function(data) {
                    for (var i = 0; i < data.d.Groups.results.length; i++) {

                        if (data.d.Groups.results[i].Title == UserGroup) {
                         
                          reactHandler.setState({ UserInGroup: !reactHandler.state.UserInGroup });
                          console.log(reactHandler.state.UserInGroup);
                        }
                    }

                },
                error: function(response) {
                    console.log(response.status);
                    
                },
            });
        //return UserInGroup;
    }

Below is my render code where need to show and hide li

public render(): React.ReactElement<IHomePageProps> {
    <li>
       <div>test</div>
    </li>
}

1 Answer 1

1

Use code like below in render() method:

{
    this.state.UserInGroup ? <li> <div> test </div> </li> : <></>
}

Check below links for conditional rendering in react:

  1. Conditional Rendering
  2. Conditional Rendering in React

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.