aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/molecules/forms/labelled-select.tsx
blob: a12956c0267cbddce2cf98f5e8379a787ab5aeb5 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { FC } from 'react';
import Label, { type LabelProps } from '../../atoms/forms/label';
import Select, { type SelectProps } from '../../atoms/forms/select';
import styles from './labelled-select.module.scss';

export type LabelledSelectProps = Omit<
  SelectProps,
  'aria-labelledby' | 'className'
> & {
  /**
   * The field label.
   */
  label: string;
  /**
   * Set additional classnames to the label.
   */
  labelClassName?: LabelProps['className'];
  /**
   * The label position. Default: top.
   */
  labelPosition?: 'left' | 'top';
  /**
   * The label size.
   */
  labelSize?: LabelProps['size'];
  /**
   * Set additional classnames to the select field.
   */
  selectClassName?: SelectProps['className'];
};

/**
 * LabelledSelect component
 *
 * Render a select with a label.
 */
const LabelledSelect: FC<LabelledSelectProps> = ({
  id,
  label,
  labelClassName = '',
  labelPosition = 'top',
  labelSize,
  required,
  selectClassName = '',
  ...props
}) => {
  const positionModifier = `label--${labelPosition}`;

  return (
    <>
      <Label
        htmlFor={id}
        required={required}
        size={labelSize}
        className={`${styles[positionModifier]} ${labelClassName}`}
      >
        {label}
      </Label>
      <Select
        id={id}
        required={required}
        {...props}
        className={selectClassName}
      />
    </>
  );
};

export default LabelledSelect;