Back to Grafana

Field

packages/grafana-ui/src/components/Forms/Field.mdx

13.1.03.0 KB
Original Source

import { Meta, ArgTypes } from '@storybook/addon-docs/blocks'; import { Field } from './Field'; import { Input } from '../Input/Input'; import { ExampleFrame } from '../../utils/storybook/ExampleFrame';

<Meta title="MDX|Field" component={Field} />

Field

Field is the basic component for rendering form elements together with labels and description.

When to use

The Field component is suitable for various scenarios where you need to incorporate form inputs into your application. Some common use cases include:

  • Creating forms with labeled input elements.
  • Adding descriptions to help users understand the purpose of the input.
  • Applying validation and error messages to form fields.
  • Indicating loading or disabled states for input fields.

Usage

<ExampleFrame> <Field label="API key" description="Your instance API key"> <Input id="api-key" /> </Field> </ExampleFrame>

Do's

  • Provide a meaningful label for the field to enhance accessibility.
  • Provide a description for the field to help users understand the purpose of the input.

Don'ts

  • Use the description prop without also providing a label.
  • Use the invalid prop without also providing an error message.

Validation

Use the invalid prop to indicate that the input is invalid. This will add a red border to the input and display the error message provided in the error prop. For this to work, both the invalid and error props must be set.

Loading

Use the loading prop to indicate that the input is loading. This will add a spinner to the input.

Props

<ArgTypes of={Field} />

FieldContext

Field provides a FieldContext that any descendant can read using the useFieldContext hook. This is the recommended way to access field state from a child component.

PropertyTypeDescription
idstringResolved input id (htmlFor → child id → generated id)
invalidboolean | undefinedMirrors the invalid prop
disabledboolean | undefinedMirrors the disabled prop
loadingboolean | undefinedMirrors the loading prop
aria-describedbystring | undefinedSet when both invalid and error are truthy
aria-labelledbystring | undefinedAlways undefined in Field

Example:

jsx
import { useFieldContext } from '@grafana/ui';

function MyCustomInput() {
  const { id, invalid, disabled, 'aria-describedby': describedby } = useFieldContext();
  return <input id={id} aria-invalid={invalid} disabled={disabled} aria-describedby={describedby} />;
}

// Usage:
<Field label="Name" invalid error="Required">
  <MyCustomInput />
</Field>;