packages/grafana-ui/src/components/Forms/Field.mdx
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 is the basic component for rendering form elements together with labels and description.
The Field component is suitable for various scenarios where you need to incorporate form inputs into your application. Some common use cases include:
description prop without also providing a label.invalid prop without also providing an error message.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.
Use the loading prop to indicate that the input is loading. This will add a spinner to the input.
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.
| Property | Type | Description |
|---|---|---|
id | string | Resolved input id (htmlFor → child id → generated id) |
invalid | boolean | undefined | Mirrors the invalid prop |
disabled | boolean | undefined | Mirrors the disabled prop |
loading | boolean | undefined | Mirrors the loading prop |
aria-describedby | string | undefined | Set when both invalid and error are truthy |
aria-labelledby | string | undefined | Always undefined in Field |
Example:
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>;