> ## 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.

# Radio – Code

> Radio buttons are form elements for selecting one option from a set of choices.

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="radio-playground" fullWidth screenshot>
      ```tsx lines expandable theme={null}
      import { Radio } from "@servicetitan/anvil2";

      function App() {
        return (
          <Radio.Group legend="Choose fruit(s)" required onChange={console.log}>
            <Radio name="fruit" value="Apple" label="Apple" />
            <Radio name="fruit" value="Banana" label="Banana" />
            <Radio name="fruit" value="Strawberry" label="Strawberry" />
          </Radio.Group>
        );
      }

      export default App;
      ```
    </LiveCode>

    ## Common Examples

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

    function ExampleComponent() {
      return (
        <Radio.Group Group legend="Preferred method of communication">
          <Radio name="comm" label="Email" defaultChecked />
          <Radio name="comm" label="Phone" />
          <Radio name="comm" label="Text" />
        </Radio.Group>
      );
    }
    ```

    ### Basic radio input

    The `Radio` component accepts many of the same props as an HTML `input` with `type="radio"`, such as `name`, `value`, `checked`, and `defaultChecked`.

    <LiveCode showCode example="radio-html" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Radio } from "@servicetitan/anvil2";

      function App() {
        return <Radio value="value-default" label="Default" />;
      }

      export default App;
      ```
    </LiveCode>

    ### Controlling radio state

    Use the `checked` and `onClick` props to manually control the state of a radio.

    <LiveCode showCode example="radio-controlled" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Radio, type RadioState } from "@servicetitan/anvil2";
      import { useState } from "react";

      function App() {
        const [list, setList] = useState([
          {
            label: "Email",
            checked: false,
          },
          {
            label: "Text",
            checked: true,
          },
        ]);

        const handleUpdate = (_state: RadioState | undefined, index: number) => {
          setList((prev) =>
            prev.map((item, i) => ({
              label: item.label,
              checked: index === i,
            })),
          );
        };

        return (
          <Radio.Group legend="Preferred communication method" required>
            {list.map((item, i) => {
              return (
                <Radio
                  key={i}
                  checked={item.checked}
                  label={item.label}
                  onChange={(_e, state) => handleUpdate(state, i)}
                />
              );
            })}
          </Radio.Group>
        );
      }

      export default App;
      ```
    </LiveCode>

    ### Using radio groups

    The `Radio.Group` component acts as a wrapper around a collection of `Radio` components.

    <LiveCode showCode example="radio-radiogroup" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Radio } from "@servicetitan/anvil2";

      function App() {
        return (
          <Radio.Group legend="Choose a taco" required>
            <Radio name="taco" value="asada" label="Carne Asada" />
            <Radio name="taco" value="pollo" label="Pollo" />
          </Radio.Group>
        );
      }

      export default App;
      ```
    </LiveCode>

    ## React Accessibility

    * The `Radio` component's `label` prop allows for any `ReactElement` to be passed in, but the `label` should always be populated with some text content that is screen-reader accessible.

    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).

    ### Markdown in legends

    The `Radio.Group` `legend` prop supports inline markdown: bold (`**text**`), italic (`*text*`), bold and italic (`***text***`), highlight (`==text==`), and code (`` `text` ``).

    <LiveCode showCode example="radio-group-markdownlabel" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Flex, Radio } from "@servicetitan/anvil2";

      function App() {
        return (
          <Flex direction="column" gap="6">
            <Radio.Group legend="**Bold** legend">
              <Radio name="bold" value="a" label="Option A" />
              <Radio name="bold" value="b" label="Option B" />
            </Radio.Group>
            <Radio.Group legend="*Italic* legend">
              <Radio name="italic" value="a" label="Option A" />
              <Radio name="italic" value="b" label="Option B" />
            </Radio.Group>
            <Radio.Group legend="***Bold and italic*** legend">
              <Radio name="bolditalic" value="a" label="Option A" />
              <Radio name="bolditalic" value="b" label="Option B" />
            </Radio.Group>
            <Radio.Group legend="==Highlight== legend">
              <Radio name="highlight" value="a" label="Option A" />
              <Radio name="highlight" value="b" label="Option B" />
            </Radio.Group>
            <Radio.Group legend="`Code` legend">
              <Radio name="code" value="a" label="Option A" />
              <Radio name="code" value="b" label="Option B" />
            </Radio.Group>
          </Flex>
        );
      }

      export default App;
      ```
    </LiveCode>

    ### Hide the legend

    Use `hideLabel` on `Radio.Group` to visually hide the legend. The `legend` string is kept as a screen-reader-only `<legend>` element so the group remains accessible — any inline markdown is stripped to plain text.

    <LiveCode showCode example="radio-group-hidelabel" screenshot fullWidth>
      ```tsx lines expandable theme={null}
      import { Radio } from "@servicetitan/anvil2";

      function App() {
        return (
          <Radio.Group legend="Payment method" hideLabel flexDirection="row">
            <Radio name="payment" value="cc" label="Credit card" />
            <Radio name="payment" value="bank" label="Bank transfer" />
            <Radio name="payment" value="paypal" label="PayPal" />
          </Radio.Group>
        );
      }

      export default App;
      ```
    </LiveCode>
  </Tab>

  <Tab title="Radio Props">
    ```tsx theme={null}
    <Radio
      name="option"
      label="Option 1"
      value="option1"
      defaultChecked={false}
      checked={false}
      error={false}
      icons={{ checked: CheckIcon, unchecked: UncheckIcon }}
      onChange={(e, state) => console.log(state)}
    />
    ```

    ## `Radio` Props

    In addition to the props listed below, the `Radio` component can accept any valid HTML `input` props.

    <ParamField path="onChange" type="(e: ChangeEvent, state: { checked: boolean; value: string | string[] | number }) => void" required>
      Callback when the radio is changed.
    </ParamField>

    <ParamField path="checked" type="boolean" default="false">
      Controlled checked state.
    </ParamField>

    <ParamField path="defaultChecked" type="boolean" default="false">
      Uncontrolled checked state.
    </ParamField>

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

    <ParamField path="error" type="boolean">
      Error state for the radio.
    </ParamField>

    <ParamField path="icons" type="{ checked?: Svg; unchecked?: Svg }">
      Overrides for default icons.
    </ParamField>

    <ParamField path="label" type="ReactElement | string">
      The `label` should have accessible `string` content.
    </ParamField>
  </Tab>

  <Tab title="Radio.Group Props">
    ```tsx theme={null}
    <Radio.Group
      legend="Select an option"
      moreInfo="Additional information"
      required={false}
    >
      <Radio name="option" label="Option 1" />
      <Radio name="option" label="Option 2" />
    </Radio.Group>
    ```

    ## `Radio.Group` Props

    In addition to the props listed below, the `Radio.Group` component can accept any valid HTML `fieldset` props.

    <ParamField path="legend" type="ReactElement | string" required>
      The legend for the radio group. Supports inline markdown formatting.

      <Warning>Passing `ReactElement` is deprecated — use a plain string with inline markdown instead.</Warning>
    </ParamField>

    <ParamField path="hideLabel" type="boolean" default="false">
      Visually hides the legend while keeping it accessible to screen readers.
    </ParamField>

    <ParamField path="legendProps" type={`Omit<FieldLabelProps, "el">`}>
      Additional props to pass to the legend [FieldLabel](/docs/web/components/field-label/code) component. Supports the `aiMark` prop for displaying [AI-powered field indicators](/docs/web/utilities/ai-marks).
    </ParamField>

    <ParamField path="required" type="boolean" />
  </Tab>
</Tabs>
