JGuang

Tabs

Tabs · Mantine Core

Preview
npm install @mantine/core@9.7.1 @mantine/hooks@9.7.1

Tabs

Install: npm install @mantine/core@9.7.1 @mantine/hooks@9.7.1

Version and compatibility

Pinned Mantine Core 9.7.1 requires React and React DOM ^19.2.0 and matching @mantine/hooks@9.7.1, from the installed npm package's peerDependencies. Do not force it into React 18 or another incompatible version. Explain upgrade impact and agree on a plan with the project owner; do not hide conflicts with --force/--legacy-peer-deps. The native Provider enables theme.respectReducedMotion and uses forceColorScheme for light/dark.

Use case

Switch between mutually exclusive panels.

Native props used by this example

These props are extracted from the local typechecked JSX and grouped by their owning native component. This is not an exhaustive prop list; see pinned source signatures and inheritance below.

Component propExplanation
Tabs.defaultValueInitial uncontrolled value, not a live controlled update.
Tabs.Tab.valueControlled value; the native type defines its shape.
Tabs.Panel.valueControlled value; the native type defines its shape.
Tabs.Panel.ptMantine top-padding style prop.

Interaction and state checks

Current scenarios: Default. Check actual behavior after selecting supported disabled/error/read-only scenarios; components without those native states do not receive invented universal props. Verify keyboard focus and exits, then connect changed values through the native callback signature.

Business integration boundary

Demo content/state is local, without server persistence, authorization or fetching. A static display component is not a completed business workflow.

Host setup

Install pinned @mantine/core and @mantine/hooks, import @mantine/core/styles.css at the entry and use MantineProvider. The example's theme/variant are JGuang-authored host props, not universal native component APIs; forceColorScheme synchronizes the app theme. Native implementation source is a reading reference: use npm exports rather than copying internal engines. This batch covers Core, not dates/charts/forms extension packages. Detailed upstream prose remains English.

Runnable usage

import { useState } from 'react';
import * as M from '@mantine/core';
import '@mantine/core/styles.css';


function ComponentPreview({ variant = 'Default' }: { variant?: string }) {
const [value, setValue] = useState(35);
const content = <M.Text>Build something beautiful / 构建美好的界面</M.Text>;
return <M.Tabs defaultValue="preview"><M.Tabs.List><M.Tabs.Tab value="preview">Preview</M.Tabs.Tab><M.Tabs.Tab value="code">Code</M.Tabs.Tab></M.Tabs.List><M.Tabs.Panel value="preview" pt="md">{content}</M.Tabs.Panel><M.Tabs.Panel value="code" pt="md"><M.Code>npm install @mantine/core</M.Code></M.Tabs.Panel></M.Tabs>;
}
export default function Example({ variant = 'Default', theme = 'light' }: { variant?: string; theme?: 'light' | 'dark' }) {
return <M.MantineProvider forceColorScheme={theme} theme={{ respectReducedMotion: true }}><ComponentPreview variant={variant} /></M.MantineProvider>;
}

Preview states

Default

The example uses the native Mantine API. For supported input demos, change the local variant to Disabled, Invalid or Read only; these are example labels, not new component props. Keep the documented data, controlled values, stores and compound children when adapting the example.

Usage

Controlled Tabs

To control the Tabs state, use value and onChange props:

import { useState } from 'react';
import { Tabs } from '@mantine/core';

function Demo() {
  const [activeTab, setActiveTab] = useState<string | null>('first');

  return (
    <Tabs value={activeTab} onChange={setActiveTab}>
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>

      <Tabs.Panel value="first">First panel</Tabs.Panel>
      <Tabs.Panel value="second">Second panel</Tabs.Panel>
    </Tabs>
  );
}

Uncontrolled Tabs

If you do not need to subscribe to Tabs state changes, use defaultValue:

import { Tabs } from '@mantine/core';

function Demo() {
  return (
    <Tabs defaultValue="first">
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>

      <Tabs.Panel value="first">First panel</Tabs.Panel>
      <Tabs.Panel value="second">Second panel</Tabs.Panel>
    </Tabs>
  );
}

Change colors

To change the colors of all tabs, set color on the Tabs component; to change the color of an individual tab, set color on Tabs.Tab.

Tabs position

To display a tab on the opposite side, set margin-left: auto with the ml="auto" prop or with className:

Inverted tabs

To make tabs inverted, place Tabs.Panel components before Tabs.List and add the inverted prop to the Tabs component:

Vertical tabs placement

To change the placement of Tabs.List in vertical orientation, set the placement prop:

Custom variants

Example of custom variant with FloatingIndicator:

Disabled tabs

Set the disabled prop on the Tabs.Tab component to disable a tab. Disabled tabs cannot be activated with the mouse or keyboard, and they will be skipped when the user navigates with arrow keys:

Activation mode

By default, tabs are activated when the user presses arrow keys or Home/End keys. To disable that, set activateTabWithKeyboard={false} on the Tabs component:

Tab deactivation

By default, the active tab cannot be deactivated. To allow that, set allowTabDeactivation on the Tabs component:

Unmount inactive tabs

By default, inactive Tabs.Panel will stay mounted; to unmount inactive tabs, set keepMounted={false} on Tabs. This is useful when you want to render components that impact performance inside Tabs.Panel. Note that components that are rendered inside Tabs.Panel will reset their state on each mount (tab change).

import { Tabs } from '@mantine/core';

// Second tab panel will be mounted only when the user activates the second tab
function Demo() {
  return (
    <Tabs keepMounted={false} defaultValue="first">
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>

      <Tabs.Panel value="first">First panel</Tabs.Panel>
      <Tabs.Panel value="second">Second panel</Tabs.Panel>
    </Tabs>
  );
}

Get tab control ref

import { useRef } from 'react';
import { Tabs } from '@mantine/core';

function Demo() {
  const secondTabRef = useRef<HTMLButtonElement>(null);

  return (
    <Tabs defaultValue="first">
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="Second" ref={secondTabRef}>
          Second tab
        </Tabs.Tab>
        <Tabs.Tab value="third">Third tab</Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

You can render Tabs.Tab as an a element by using the renderRoot prop. This gives you native link behavior: right-click to open in a new tab, middle-click, and href for crawlers and accessibility.

import { Tabs } from '@mantine/core';

function Demo() {
  return (
    <Tabs defaultValue="home">
      <Tabs.List>
        <Tabs.Tab
          value="home"
          renderRoot={(props) => <a href="/home" {...props} />}
        >
          Home
        </Tabs.Tab>
        <Tabs.Tab
          value="about"
          renderRoot={(props) => <a href="/about" {...props} />}
        >
          About
        </Tabs.Tab>
        <Tabs.Tab
          value="contacts"
          renderRoot={(props) => <a href="/contacts" {...props} />}
        >
          Contacts
        </Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

You can also use the component prop to render tabs as links:

import { Tabs } from '@mantine/core';

function Demo() {
  return (
    <Tabs defaultValue="home">
      <Tabs.List>
        <Tabs.Tab value="home" component="a" href="/home">
          Home
        </Tabs.Tab>
        <Tabs.Tab value="about" component="a" href="/about">
          About
        </Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Use the renderRoot prop to render Tabs.Tab as a Next.js Link component. The renderRoot prop is required instead of component because Next.js Link is a generic component:

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Tabs } from '@mantine/core';

function Demo() {
  const pathname = usePathname();

  return (
    <Tabs value={pathname}>
      <Tabs.List>
        <Tabs.Tab
          value="/home"
          renderRoot={(props) => <Link href="/home" {...props} />}
        >
          Home
        </Tabs.Tab>
        <Tabs.Tab
          value="/about"
          renderRoot={(props) => <Link href="/about" {...props} />}
        >
          About
        </Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Use the renderRoot prop to render Tabs.Tab as a React Router NavLink or Link component:

import {
  Link,
  Route,
  useLocation,
} from 'react-router-dom';
import { Tabs } from '@mantine/core';

// Route: <Route path="/tabs/:tabValue" element={<Demo />} />

function Demo() {
  const location = useLocation();

  return (
    <Tabs value={location.pathname}>
      <Tabs.List>
        <Tabs.Tab
          value="/tabs/first"
          renderRoot={(props) => (
            <Link to="/tabs/first" {...props} />
          )}
        >
          First tab
        </Tabs.Tab>
        <Tabs.Tab
          value="/tabs/second"
          renderRoot={(props) => (
            <Link to="/tabs/second" {...props} />
          )}
        >
          Second tab
        </Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Usage with react-router

<Route path="/tabs/:tabValue" element={<Demo />} />
import { useNavigate, useParams } from 'react-router-dom';
import { Tabs } from '@mantine/core';

function Demo() {
  const navigate = useNavigate();
  const { tabValue } = useParams();

  return (
    <Tabs
      value={tabValue}
      onChange={(value) => navigate(`/tabs/${value}`)}
    >
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Usage with Next.js Pages Router

// For file /tabs/[activeTab].tsx
import { useRouter } from 'next/router';
import { Tabs } from '@mantine/core';

function Demo() {
  const router = useRouter();

  return (
    <Tabs
      value={router.query.activeTab as string}
      onChange={(value) => router.push(`/tabs/${value}`)}
    >
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Usage with Next.js App Router

In the App Router, get the current tab value from the pathname with the usePathname hook and change tabs with the router returned by useRouter. Both hooks are imported from next/navigation. Note that components that use these hooks must be Client Components (add the 'use client' directive at the top of the file).

// For file /tabs/[activeTab]/page.tsx
'use client';

import { usePathname, useRouter } from 'next/navigation';
import { Tabs } from '@mantine/core';

function Demo() {
  const router = useRouter();
  const pathname = usePathname();
  const activeTab = pathname.split('/').pop();

  return (
    <Tabs
      value={activeTab}
      onChange={(value) => router.push(`/tabs/${value}`)}
    >
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Example of Styles API usage to customize tab styles:

Example with Scroller component

Use Scroller component to make the tabs list scrollable when there are too many tabs to fit in the available space:

Accessibility

The Tabs component follows WAI-ARIA recommendations on accessibility.

When Tabs.Tab is rendered as a link (<a> tag), the role="tab" attribute overrides the implicit link role. Screen readers will announce the element as a "tab", not a "link". This is the expected behavior per the WAI-ARIA specification.

When using tabs as navigation links without Tabs.Panel components, the aria-controls attribute on each tab references a panel element that does not exist in the DOM. This is a minor accessibility consideration – most screen readers handle this gracefully.

If you use Tabs.Tab without text content, for example, only with an icon, then set aria-label or use the VisuallyHidden component:

import { CoinIcon } from '@phosphor-icons/react';
import { Tabs, VisuallyHidden } from '@mantine/core';

function Demo() {
  return (
    <Tabs defaultValue="chat">
      <Tabs.List>
        {/* aria-label is not required, tab is labelled by children */}
        <Tabs.Tab value="chat">Chat</Tabs.Tab>

        {/* aria-label is required, tab is not labelled by children */}
        <Tabs.Tab
          value="money"
          aria-label="Get money"
          leftSection={<CoinIcon size={14} />}
        />

        {/* You can use VisuallyHidden instead of aria-label */}
        <Tabs.Tab value="money" leftSection={<CoinIcon size={14} />}>
          <VisuallyHidden>Get money</VisuallyHidden>
        </Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

To set the tabs list label, set aria-label on the Tabs.List component; it will be announced by screen reader:

import { Tabs } from '@mantine/core';

function Demo() {
  return (
    <Tabs defaultValue="recent">
      {/* Tabs.List aria-label will be announced when tab is focused for the first time */}
      <Tabs.List aria-label="Chats">
        <Tabs.Tab value="recent">Most recent</Tabs.Tab>
        <Tabs.Tab value="recent">Unanswered</Tabs.Tab>
        <Tabs.Tab value="archived">Archived</Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

Keyboard interactions

Source-backed parameter reference

Implementation signatures and types are generated from the pinned local source. Optional props, native inherited types, union branches and never exclusions are preserved. A forwardRef implementation's ref is a React reference, not an additional business prop.

Tabs(_props)
export type TabsStylesNames =
  | 'root'
  | TabsListStylesNames
  | TabsPanelStylesNames
  | TabsTabStylesNames;

export type TabsVariant = 'default' | 'outline' | 'pills';

export type TabsCssVariables = {
  root: '--tabs-color' | '--tabs-radius';
};

export interface TabsProps
  extends
    BoxProps,
    StylesApiProps<TabsFactory>,
    ElementProps<'div', 'defaultValue' | 'value' | 'onChange'> {
  /** Uncontrolled component default value */
  defaultValue?: string | null;

  /** Controlled component value */
  value?: string | null;

  /** Called when value changes */
  onChange?: (value: string | null) => void;

  /** Tabs orientation @default 'horizontal' */
  orientation?: 'vertical' | 'horizontal';

  /** `Tabs.List` placement relative to `Tabs.Panel`, applicable only when `orientation="vertical"` @default 'left' */
  placement?: 'left' | 'right';

  /** Base id, used to generate ids to connect labels with controls, generated randomly by default */
  id?: string;

  /** If set, arrow key presses loop though items (first to last and last to first) @default true */
  loop?: boolean;

  /** If set, tab is activated with arrow key press @default true */
  activateTabWithKeyboard?: boolean;

  /** If set, tab can be deactivated @default false */
  allowTabDeactivation?: boolean;

  /** Tabs content */
  children?: React.ReactNode;

  /** Changes colors of `Tabs.Tab` components when variant is `pills` or `default`, does nothing for other variants */
  color?: MantineColor;

  /** Key of `theme.radius` or any valid CSS value to set `border-radius` @default theme.defaultRadius */
  radius?: MantineRadius;

  /** Determines whether tabs should have inverted styles @default false */
  inverted?: boolean;

  /** If set to `false`, `Tabs.Panel` content will be unmounted when the associated tab is not active @default true */
  keepMounted?: boolean;

  /** Controls how inactive tabs content is hidden when `keepMounted` is `true`, `'activity'` – hidden with `Activity` component, `'display-none'` – hidden with `display: none` styles @default 'activity' */
  keepMountedMode?: 'activity' | 'display-none';

  /** If set, adjusts text color based on background color for `pills` variant */
  autoContrast?: boolean;
}

export type TabsFactory = Factory<{
  props: TabsProps;
  ref: HTMLDivElement;
  variant: TabsVariant;
  stylesNames: TabsStylesNames;
  vars: TabsCssVariables;
  staticComponents: {
    Tab: typeof TabsTab;
    Panel: typeof TabsPanel;
    List: typeof TabsList;
  };
}>;

export type Mod = Record<string, any> | string;

export type BoxMod = Mod | Mod[] | BoxMod[];

export interface BoxProps extends MantineStyleProps {
  /** Class added to the root element, if applicable */
  className?: string | undefined;

  /** Inline style added to root component element, can subscribe to theme defined on MantineProvider */
  style?: MantineStyleProp;

  /** CSS variables defined on root component element */
  __vars?: CssVarsProp;

  /** `size` property passed down the HTML element */
  __size?: string;

  /** Breakpoint above which the component is hidden with `display: none` */
  hiddenFrom?: MantineBreakpoint;

  /** Breakpoint below which the component is hidden with `display: none` */
  visibleFrom?: MantineBreakpoint;

  /** Determines whether component should be hidden in light color scheme with `display: none` */
  lightHidden?: boolean;

  /** Determines whether component should be hidden in dark color scheme with `display: none` */
  darkHidden?: boolean;

  /** Element modifiers transformed into `data-` attributes, for example, `{ 'data-size': 'xl' }`, falsy values are removed */
  mod?: BoxMod;
}

export type ElementProps<
  ElementType extends React.ElementType,
  PropsToOmit extends string = never,
> = Omit<React.ComponentProps<ElementType>, 'style' | PropsToOmit>;

export interface CSSProperties extends React.CSSProperties {
  [key: string]: any;
}

type MantineStyle = CSSProperties | ((theme: MantineTheme) => CSSProperties);

export type MantineStyleProp = MantineStyle | MantineStyle[] | MantineStyleProp[] | undefined;

export type CssVariable = `--${string}`;

export type CssVariables<Variable extends string = CssVariable> = Partial<Record<Variable, string>>;

export type CssVars<Variable extends string = CssVariable> =
  | CssVariables<Variable>
  | ((theme: MantineTheme) => CssVariables<Variable>)
  | CssVars<Variable>[];

export type CssVarsProp<Variable extends string = CssVariable> =
  | CssVars<Variable>
  | CssVars<Variable>[];

Native and external types

External types remain defined by React or native dependencies, not manually expanded into guessed props. The installed version's TypeScript definitions are authoritative.

Factory<{
  props: TabsProps;
  ref: HTMLDivElement;
  variant: TabsVariant;
  stylesNames: TabsStylesNames;
  vars: TabsCssVariables;
  staticComponents: {
    Tab: typeof TabsTab;
    Panel: typeof TabsPanel;
    List: typeof TabsList;
  };
}>
MantineStyleProps
React.CSSProperties
MantineTheme
Partial<Record<Variable, string>>
Record<Variable, string>
Variable
MantineBreakpoint
Record<string, any>
StylesApiProps<TabsFactory>
React.ElementType
Omit<React.ComponentProps<ElementType>, 'style' | PropsToOmit>
React.ComponentProps<ElementType>
ElementType
PropsToOmit
React.ReactNode
MantineColor
MantineRadius
HTMLDivElement
TabsListStylesNames
TabsPanelStylesNames
TabsTabStylesNames