/** * External dependencies */ import { Fragment } from '@wordpress/element'; import classNames from 'classnames'; import type { ReactElement, HTMLAttributes } from 'react'; interface LabelProps { label?: string; screenReaderLabel?: string; wrapperElement?: string; wrapperProps?: HTMLAttributes< HTMLElement >; } /** * Component used to render an accessible text given a label and/or a * screenReaderLabel. The wrapper element and wrapper props can also be * specified via props. * */ const Label = ( { label, screenReaderLabel, wrapperElement, wrapperProps = {}, }: LabelProps ): ReactElement => { let Wrapper; const hasLabel = typeof label !== 'undefined' && label !== null; const hasScreenReaderLabel = typeof screenReaderLabel !== 'undefined' && screenReaderLabel !== null; if ( ! hasLabel && hasScreenReaderLabel ) { Wrapper = wrapperElement || 'span'; wrapperProps = { ...wrapperProps, className: classNames( wrapperProps.className, 'screen-reader-text' ), }; return { screenReaderLabel }; } Wrapper = wrapperElement || Fragment; if ( hasLabel && hasScreenReaderLabel && label !== screenReaderLabel ) { return ( { screenReaderLabel } ); } return { label }; }; export default Label;