aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/molecules/forms/labelled-field.tsx
blob: fca1c543401203fb867675286cba0f183ef9e9e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { forwardRef, ForwardRefRenderFunction } from 'react';
import { Field, type FieldProps, Label } from '../../atoms';
import styles from './labelled-field.module.scss';

export type LabelledFieldProps = FieldProps & {
  /**
   * Visually hide the field label. Default: false.
   */
  hideLabel?: boolean;
  /**
   * The field label.
   */
  label: string;
  /**
   * The label position. Default: top.
   */
  labelPosition?: 'left' | 'top';
};

const LabelledFieldWithRef: ForwardRefRenderFunction<
  HTMLInputElement,
  LabelledFieldProps
> = (
  { hideLabel = false, id, label, labelPosition = 'top', required, ...props },
  ref
) => {
  const positionModifier = `label--${labelPosition}`;
  const visibilityClass = hideLabel ? 'screen-reader-text' : '';

  return (
    <>
      <Label
        htmlFor={id}
        required={required}
        className={`${visibilityClass} ${styles[positionModifier]}`}
      >
        {label}
      </Label>
      <Field id={id} ref={ref} required={required} {...props} />
    </>
  );
};

/**
 * LabelledField component
 *
 * Render a field tied to a label.
 */
export const LabelledField = forwardRef(LabelledFieldWithRef);