> ## Documentation Index
> Fetch the complete documentation index at: https://anvil.servicetitan.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Switch – Code

> Switches toggle between two states, providing immediate user feedback.

export const LiveCode = ({children, customHeight, clickToLoad, example, fullWidth, fullHeight, hideCodeInLiveCode, screenshot, screenshotOnly, showCode: showCodeProp}) => {
  const SCREENSHOTS_BASE = "https://servicetitan.github.io/anvil2-docs-live-code/screenshots";
  const STACKBLITZ_BASE = "https://stackblitz.com/github/servicetitan/anvil2-docs-live-code/tree/main/examples";
  const [showCodeBlock, setShowCodeBlock] = useState(showCodeProp ?? false);
  const [isLocalOverride, setIsLocalOverride] = useState(false);
  useEffect(() => {
    const examplePath = `/images/live-code-screenshots-tmp/${example}.png`;
    fetch(examplePath, {
      method: "HEAD"
    }).then(r => {
      if (r.ok) setIsLocalOverride(true);
    }).catch(() => {});
  }, [example]);
  const screenshotBase = isLocalOverride ? "/images/live-code-screenshots-tmp" : SCREENSHOTS_BASE;
  if (screenshotOnly) {
    return <Frame className="flex flex-col">
        <div className="flex dark:hidden" style={{
      justifyContent: "center",
      alignItems: "center",
      width: fullWidth ? "100%" : "50%",
      minHeight: fullHeight ? "284px" : undefined,
      background: "#FFFFFF"
    }}>
          <img srcset={`${screenshotBase}/${example}.png, ${screenshotBase}/${example}-2x.png 2x`} src={`${screenshotBase}/${example}.png`} alt={example} noZoom />
        </div>
        <div className="hidden dark:flex" style={{
      justifyContent: "center",
      alignItems: "center",
      width: fullWidth ? "100%" : "50%",
      minHeight: fullHeight ? "284px" : undefined,
      background: "#141414"
    }}>
          <img srcset={`${screenshotBase}/${example}-dark.png, ${screenshotBase}/${example}-dark-2x.png 2x`} src={`${screenshotBase}/${example}-dark.png`} alt={example} noZoom />
        </div>
      </Frame>;
  }
  if (screenshot) {
    return <Frame className="flex flex-col -mb-2">
        <div className="flex dark:hidden bg-white dark:bg-codeblock border border-gray-950/10 dark:border-white/10 dark:twoslash-dark rounded-2xl overflow-hidden" style={{
      justifyContent: "center",
      alignItems: "center",
      width: fullWidth ? "100%" : "50%",
      minHeight: fullHeight ? "284px" : undefined
    }}>
          <img srcset={`${screenshotBase}/${example}.png, ${screenshotBase}/${example}-2x.png 2x`} src={`${screenshotBase}/${example}.png`} alt={example} noZoom />
        </div>

        <div className="hidden dark:flex bg-white dark:bg-codeblock border border-gray-950/10 dark:border-white/10 dark:twoslash-dark rounded-2xl overflow-hidden" style={{
      background: "#141414",
      justifyContent: "center",
      alignItems: "center",
      width: fullWidth ? "100%" : "50%",
      minHeight: fullHeight ? "284px" : undefined
    }}>
          <img srcset={`${screenshotBase}/${example}-dark.png, ${screenshotBase}/${example}-dark-2x.png 2x`} src={`${screenshotBase}/${example}-dark.png`} alt={example} noZoom />
        </div>

        <div className="flex justify-end items-center text-xs py-2 px-1 gap-4">
          {!showCodeProp ? <button className="inline-flex justify-end items-center text-gray-700 dark:text-gray-50 hover:text-blue-500 dark:hover:text-blue-300 transition-colors group self-end gap-1 cursor-pointer" onClick={() => setShowCodeBlock(!showCodeBlock)} style={{
      appearance: "none"
    }}>
              <Icon icon="code" size="12px" className="group-hover:bg-blue-500 dark:group-hover:bg-blue-300" />
              <span>{showCodeBlock ? "Hide code" : "Show code"}</span>
            </button> : null}

          <a className="inline-flex justify-end items-center hover:text-blue-500 dark:hover:text-blue-300 transition-colors group self-end gap-1" href={`${STACKBLITZ_BASE}/${example}?file=src/App.tsx`} target="_blank" rel="noreferrer">
            <Icon icon="bolt" size="12px" className="group-hover:bg-blue-500 dark:group-hover:bg-blue-300" />
            <span>StackBlitz demo</span>
          </a>
        </div>

        <div className="grid transition-[grid-template-rows] duration-300 ease-in-out overflow-auto overflow-y-hidden overflow-x-auto" style={showCodeBlock ? {
      gridTemplateRows: "1fr"
    } : {
      gridTemplateRows: "0fr"
    }}>
          <div style={{
      minHeight: 0,
      overflowX: "auto",
      overflowY: "hidden",
      marginBlockStart: "-1.25rem",
      marginBlockEnd: "-1.5rem"
    }}>
            {children}
          </div>
        </div>
      </Frame>;
  } else {
    return <div style={{
      display: "flex",
      width: fullWidth ? "100%" : "50%",
      minHeight: customHeight ? customHeight : "316px",
      resize: "vertical",
      overflow: "auto"
    }}>
        <iframe title={example} style={{
      flex: 1,
      width: fullWidth ? "100%" : "50%",
      minHeight: customHeight ? customHeight : "316px"
    }} src={`${STACKBLITZ_BASE}/${example}?embed=1&hideNavigation=1&hideExplorer=1&terminalHeight=0&file=src/App.tsx${clickToLoad ? "&ctl=1" : ""}${hideCodeInLiveCode ? "&view=preview" : ""}`} allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" />
      </div>;
  }
};

<Tabs>
  <Tab title="Implementation">
    <LiveCode showCode example="switch-playground" fullWidth screenshot>
      ```tsx lines expandable theme={null}
      import { Switch } from "@servicetitan/anvil2";

      function App() {
        return (
          <Switch
            label="Switch"
            value="example-switch"
            defaultChecked={true}
            onChange={(event, { value, checked }) => {
              console.log("\nevent:");
              console.log(event);
              console.log(`value: ${value}`);
              console.log(`checked: ${checked}`);
            }}
          />
        );
      }

      export default App;
      ```
    </LiveCode>

    ## Common Examples

    ```tsx theme={null}
    import { Switch } from "@servicetitan/anvil2";

    function ExampleComponent() {
      return <Switch defaultChecked={true} label="Switch" value="switch-example" />;
    }
    ```

    ### Controlling switches

    <LiveCode showCode example="switch-uncontrolled" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Switch, Flex, Button } from "@servicetitan/anvil2";
      import { useRef } from "react";

      function App() {
        const switchRef = useRef<HTMLInputElement>(null);

        return (
          <Flex gap={4} justifyContent="space-around">
            <Switch
              ref={switchRef}
              defaultChecked={false}
              label="Switch"
              value="switch-example"
            />
            <Button
              onClick={() => {
                if (switchRef.current != null) {
                  switchRef.current.checked = !switchRef.current.checked;
                }
              }}
            >
              Toggle Switch
            </Button>
          </Flex>
        );
      }

      export default App;
      ```
    </LiveCode>

    #### Uncontrolled switch

    By default, the state of a switch is handled internally. Use the `defaultChecked` prop to set the initial state.

    To access the current value, a React `ref` can be used. Make sure you understand [the differences between refs and state in React](https://react.dev/learn/referencing-values-with-refs#differences-between-refs-and-state).

    <LiveCode showCode example="switch-controlled" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Switch, Flex, Button } from "@servicetitan/anvil2";
      import { useState } from "react";

      function App() {
        const [checked, setChecked] = useState(false);

        return (
          <Flex gap={4} justifyContent="space-around">
            <Switch
              checked={checked}
              onChange={(_e, { checked }) => {
                setChecked(checked);
              }}
              label="Switch"
              value="switch-example"
            />
            <Button
              onClick={() => {
                setChecked((prev) => !prev);
              }}
            >
              Toggle Switch
            </Button>
          </Flex>
        );
      }

      export default App;
      ```
    </LiveCode>

    #### Controlled switch

    Alternatively, use the `checked` and `onChange` props to manually control the checked state.

    ## React Accessibility

    * The supplied `label` prop should either be text or a component containing text. If this is not possible, then either an `aria-label` should be set or a visible label should be referenced with `aria-labelledby`.
    * If the page contains additional text needed to fully understand the purpose of the `Switch`, this text should be referenced with `aria-describedby`.

    For more guidance on form field labels and context, see [input field context association best practices](/docs/accessibility/labels-and-ctas#input-field-context-association).
  </Tab>

  <Tab title="Switch Props">
    ```tsx theme={null}
    <Switch
      label="Toggle switch"
      value="switch-1"
      checked={true}
      defaultChecked={false}
      onChange={(event, { value, checked }) => console.log(value, checked)}
      disabled={false}
    />
    ```

    ## `Switch` Props

    In addition to the props listed below, the `Switch` component accepts any valid HTML `input` props.

    <ParamField path="description" type="string">
      Description text to display below the label.
    </ParamField>

    <ParamField path="label" type="ReactElement | string" />

    <ParamField path="labelAiMark" type={`boolean | AiMarkWithTooltipOrPopoverConfig`}>
      Displays an AI indicator icon next to the label. See [AI Marks](/docs/web/utilities/ai-marks) for full API documentation and usage examples.
    </ParamField>

    <ParamField path="onChange" type="(e: ChangeEvent, state: { value: string; checked: boolean }) => void">
      This replaces the default `onChange` for the HTML `input` element.
    </ParamField>
  </Tab>
</Tabs>
