Docs

Create a custom organization switcher

If you need more control than what Clerk's prebuilt <OrganizationSwitcher /> component provides, you can build your own organization switcher using the useOrganizationList() hook.

In the following example, the useOrganizationList() hook is used to fetch userMemberships, which contains a data array of the user's organizations. The data array is paginated and will only return the first 10 results, so the fetchNext() method is used to load more organizations if they are available. For more information about the properties and methods available on the userMemberships object, visit the useOrganizationList() reference page.

The example is written for Next.js App Router, but it is supported by any React meta framework, such as Remix or Gatsby.

To get started, create a new file called OrganizationSwitcher.tsx and paste the following code into it. You can place this file anywhere in your project, but in this example, it is placed in a folder called components.

app/components/OrganizationSwitcher.tsx
"use client"

import { useOrganizationList } from "@clerk/nextjs";

export const CustomOrganizationSwitcher = () => {
  const { isLoaded, setActive, userMemberships } = useOrganizationList({
    userMemberships: {
      infinite: true,
    },
  });

  if (!isLoaded) {
    return <p>Loading</p>;
  }

  return (
    <>
      <h2>Custom Organization Switcher</h2>
      <ul>
        {userMemberships.data?.map((mem) => (
          <li key={mem.id}>
            <span>{mem.organization.name}</span>
            <button
              onClick={() => setActive({ organization: mem.organization.id })}
            >
              Select
            </button>
          </li>
        ))}
      </ul>

      <button
        disabled={!userMemberships.hasNextPage}
        onClick={() => userMemberships.fetchNext()}
      >
        Load more organizations
      </button>
    </>
  );
};

Feedback

What did you think of this content?