Leaderboard

Rendering a board

The table, the pager, the fan's own row, and an XP bar that reads the right number.

One provider, one table and one row you pin. Short, because the board is read-only.

The shape

import { LEADERBOARD_KIND, Leaderboard } from '@xborglabs/fanbase-react'

export function LeaderboardPage() {
  return (
    <Leaderboard.Provider kind={LEADERBOARD_KIND.RESOURCE}>
      <MyRank />
      <Board />
      <Pager />
    </Leaderboard.Provider>
  )
}

Leaderboard.Provider reads one page of the board and, for a signed-in fan, their own position, and publishes both through useLeaderboard().

Do not pass a communityId. The provider resolves it from the slug on FanbaseProvider.

The board is public. It works for a fan who is not signed in, which makes it a good page to link from somewhere they can find it before they have an account.

The table

import { isLeaderboardViewerRow, resolveMessage, useLeaderboard } from '@xborglabs/fanbase-react'

function Board() {
  const { state } = useLeaderboard()

  if (state.isLoading) return <YourSkeleton rows={10} />
  if (state.listReason === 'SLUG_UNRESOLVED') return <p>This board is not available.</p>
  if (state.listReason === 'EMPTY') return <p>{resolveMessage('Leaderboard.empty')}</p>

  return (
    <table className="your-table">
      <thead>
        <tr>
          <th>{resolveMessage('Leaderboard.rank')}</th>
          <th>{resolveMessage('Leaderboard.username')}</th>
          <th>{state.resourceType?.name ?? resolveMessage('Leaderboard.score')}</th>
        </tr>
      </thead>
      <tbody>
        {state.users.map((row) => (
          <tr
            key={row.user.userId}
            data-me={isLeaderboardViewerRow(row, state.viewerUserId) || undefined}
          >
            <td>{row.rank ?? '·'}</td>
            <td>
              {row.equippedPersonalization?.pfp ? (
                <img src={row.equippedPersonalization.pfp.mediaUrl} alt="" width={32} height={32} />
              ) : null}
              {row.user.displayName ?? row.user.handle}
            </td>
            <td>{row.balance}</td>
          </tr>
        ))}
      </tbody>
    </table>
  )
}

A few details that are easy to get wrong:

row.rank is optional. It can be missing from a row. Render a placeholder rather than an empty cell or a 0.

Name the score column after the resource. state.resourceType?.name is what your community calls it, XP or Points or whatever they chose. The display string is the fallback.

Highlight the fan with isLeaderboardViewerRow. Put a data attribute or a class on their row and style it. It compares the row against the signed-in fan's id, which the provider reads from their membership.

That id is missing for a signed-in fan who has not joined the community, because they have no membership to read. To highlight them too, fall back to useViewer, which works for every signed-in fan:

const { data: viewer } = useViewer()

isLeaderboardViewerRow(row, state.viewerUserId ?? viewer?.userId)

The profile link is yours. FanBase has no public profile page to link to. If your product has profiles, link the name to yours.

Medals for the top three, the fan's avatar and a membership badge are all yours to draw. The row carries what you need: row.rank, row.equippedPersonalization and row.membership?.tier.

Two empty states

They look alike and mean different things.

state.listReasonMeansShow
EMPTYThe board loaded and nobody is on it yet"No one has scored yet", or similar
SLUG_UNRESOLVEDThe community's main resource is not set up, so there was no board to load"Not available". This is a configuration problem, not an empty board.

If you see SLUG_UNRESOLVED in production, the community's main resource is missing its slug in the Hub. A quests board never hits it.

Paging

limit defaults to 10. The pager buttons disable themselves at either end:

import { Leaderboard, resolveMessage, useLeaderboard } from '@xborglabs/fanbase-react'

function Pager() {
  const { state } = useLeaderboard()

  return (
    <nav className="your-pager">
      <Leaderboard.PreviousPage asChild>
        <button type="button">{resolveMessage('Leaderboard.previousPage')}</button>
      </Leaderboard.PreviousPage>

      <span>
        {resolveMessage('Leaderboard.pageOf', undefined, {
          page: state.pageMeta.page,
          totalPages: state.pageMeta.totalPages,
        })}
      </span>

      <Leaderboard.NextPage asChild>
        <button type="button">{resolveMessage('Leaderboard.nextPage')}</button>
      </Leaderboard.NextPage>
    </nav>
  )
}

For "page 3 of 12", read state.pageMeta.page, not state.page. state.page is the page you asked for. pageMeta.page is the page the platform actually sent, and if you ask for page 40 of 12, they differ.

The second argument to resolveMessage is your i18n adapter, if you have one. Pass undefined when you do not. Display strings covers both.

Keeping the page in the URL

Leave page off the provider and it keeps the page itself. That is fine until someone presses back and the table does not move.

To keep the page in the URL, pass it in and write it back out:

const page = Number(searchParams.get('page') ?? 1)

<Leaderboard.Provider
  kind={LEADERBOARD_KIND.RESOURCE}
  page={page}
  onPageChange={(next) => setSearchParams({ page: String(next) })}
>

Once you pass page, the provider does what the prop says on every render. Pass it and forget onPageChange, and the pager buttons stop working.

Jumping to the fan

A "show me" button that jumps to the page the fan is on:

import { getLeaderboardPageForRank, useLeaderboard } from '@xborglabs/fanbase-react'

const { state, actions } = useLeaderboard()
const rank = state.viewerRank?.leaderboardRank

const jump = () =>
  rank && actions.setPage(getLeaderboardPageForRank({ rank, limit: state.limit }))

It assumes every position is filled once. Ties can land it a page early or late, so treat it as close rather than exact.

The fan's own row

import { resolveMessage, useLeaderboard } from '@xborglabs/fanbase-react'

function MyRank() {
  const { state } = useLeaderboard()

  if (state.viewerReason === 'AUTH_REQUIRED') return <SignInPrompt />
  if (state.viewerReason === 'UNRANKED' || !state.viewerRank) {
    return <p>{resolveMessage('Leaderboard.unranked')}</p>
  }

  const { leaderboardRank, balance, current } = state.viewerRank

  return (
    <section className="your-my-rank">
      <h2>{resolveMessage('Leaderboard.myRank')}</h2>
      <p>
        #{leaderboardRank} · {balance}
        {current?.level != null && ` · ${resolveMessage('Leaderboard.Level')} ${current.level}`}
      </p>
    </section>
  )
}
state.viewerReasonMeansShow
AUTH_REQUIREDNot signed inA sign-in prompt. "See where you rank" is a good reason to sign in.
UNRANKEDSigned in, nothing earned yetA nudge towards their first quest

Pin this row where it is always visible. A fan at position 3,000 will never page down to find themselves.

Known gap: a signed-in fan who is not a member of the community cannot be highlighted in the table, because the id the highlight compares against comes from their membership. Their own row above still works.

XP bars elsewhere

Not on the board itself, but it trips people up. An XP bar in your nav or on a profile always reads community XP:

import { useCommunityXP } from '@xborglabs/fanbase-react'

const { data } = useCommunityXP()

Use it even when the board on screen is the quests board. The quests board's own row counts quests, not XP, and wiring an XP bar to it shows a fan's quest count as if it were their level.

Components

ComponentUse
Leaderboard.ProviderReads one page of the board and the fan's own row
Leaderboard.PreviousPagePrevious page, disabled on the first
Leaderboard.NextPageNext page, disabled on the last

Both pagers take asChild and render your element.

For a board without the provider, useLeaderboardList({ kind, page, limit }) reads a page and useLeaderboardViewerRank({ kind }) reads the fan's row. Full props in Components.

Checklist

  • The board renders with no communityId, signed in or not
  • A row with no rank shows a placeholder
  • The score column is named after the resource
  • The signed-in fan's row is highlighted in the table
  • The fan's own row is pinned and handles both signed out and unranked
  • SLUG_UNRESOLVED and EMPTY show different messages
  • The pager text reads from pageMeta, and disables at either end
  • If the page is in the URL, pressing back moves the table
  • XP bars read useCommunityXP, never the quests board

On this page