Skip to main content

<Groups>

<Groups> is a conditional rendering helper. Use this component where some content should be shown only to users belonging to one or more specific groups.

The children of <Groups> will be shown only:

  • Where belongsTo is string: the user belongs to the group name provided.
  • Where belongsTo is a function: the predicate returns true.

Usage

User belongs to admin group

import { Groups } from "@slashid/react"

function Component() {
return (
<Groups belongsTo="admin">
Only visible for admins.
</Groups>
)
}

User belongs to one of many

User belongs to either admin or user group.

We provide a static method Groups.some(...groups: string[]) so you can easily implement an inclusive OR assertion.

import { Groups } from "@slashid/react"

function Component() {
return (
<Groups belongsTo={Groups.some("admin", "user")}>
Visible to user who is either user OR admin.
</Groups>
)
}

User belongs to all

User belongs to both admin and user groups.

We provide a static method Groups.all(...groups: string[]) so you can easily implement an inclusive AND assertion.

import { Groups } from "@slashid/react"

function Component() {
return (
<Groups belongsTo={Groups.all("admin", "user")}>
Only visible to user who is both user AND admin.
</Groups>
)
}

Implementing complex group assertions

If you need more complex logic in your group check you can write your own predicate function.

import { Groups } from "@slashid/react"

function Component() {
// Using `React.useCallback` is recommended to prevent unnecessary render cycles
const customBusinessLogicAssertion = React.useCallback((groups) => {
if (groups.includes("alpha") && !groups.includes("beta")) return true
if (groups.includes("beta") && groups.includes("charlie")) return true
if (groups.includes("delta")) return true
return false
}, [])

return (
<Groups belongsTo={customBusinessLogicAssertion}>
Visible to users who satisfy custom business logic
</Groups>
)
}

Props

PropTypeDefaultDescription
belongsTostring | (groups: string[]) => booleanGroup name or predicate function which is called with a list of groups the authenticated user belongs to; return true to render the children content.