diff --git a/.changeset/polite-chicken-fix.md b/.changeset/polite-chicken-fix.md new file mode 100644 index 00000000000..a24ec9f846a --- /dev/null +++ b/.changeset/polite-chicken-fix.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +passthrough form control label props diff --git a/src/FormControl/_FormControlLabel.tsx b/src/FormControl/_FormControlLabel.tsx index bf2675b6479..85aa793513c 100644 --- a/src/FormControl/_FormControlLabel.tsx +++ b/src/FormControl/_FormControlLabel.tsx @@ -1,5 +1,5 @@ import React from 'react' -import InputLabel, {LabelProps, LegendOrSpanProps} from '../_InputLabel' +import InputLabel from '../_InputLabel' import {SxProp} from '../sx' import {FormControlContext} from './FormControl' @@ -12,21 +12,35 @@ export type Props = { } & SxProp const FormControlLabel: React.FC< - React.PropsWithChildren<{htmlFor?: string} & (LegendOrSpanProps | LabelProps) & Props> -> = ({children, htmlFor, id, visuallyHidden, sx}) => { + React.PropsWithChildren<{htmlFor?: string} & React.ComponentProps & Props> +> = ({as, children, htmlFor, id, visuallyHidden, sx, ...props}) => { const {disabled, id: formControlId, required} = React.useContext(FormControlContext) - return ( - - {children} - - ) + + /** + * Ensure we can pass through props correctly, since legend/span accept no defined 'htmlFor' + */ + const labelProps: React.ComponentProps = + as === 'legend' || as === 'span' + ? { + as, + id, + visuallyHidden, + required, + disabled, + sx, + ...props, + } + : { + as, + id, + visuallyHidden, + htmlFor: htmlFor || formControlId, + required, + disabled, + sx, + ...props, + } + return {children} } export default FormControlLabel diff --git a/src/_InputLabel.tsx b/src/_InputLabel.tsx index e1804c7398f..ae1adbd4e1f 100644 --- a/src/_InputLabel.tsx +++ b/src/_InputLabel.tsx @@ -31,6 +31,7 @@ const InputLabel: React.FC> = ({ visuallyHidden, sx, as = 'label', + ...props }) => { return ( > = ({ alignSelf: 'flex-start', ...sx, }} + {...props} > {required ? ( diff --git a/src/__tests__/FormControl.test.tsx b/src/__tests__/FormControl.test.tsx index 2898e7e3654..abd06f31bc8 100644 --- a/src/__tests__/FormControl.test.tsx +++ b/src/__tests__/FormControl.test.tsx @@ -199,6 +199,24 @@ describe('FormControl', () => { expect(input).toBeDefined() expect(label).toBeDefined() }) + + it('passes through props on the label element', () => { + const {getByLabelText, getByText} = render( + + + {LABEL_TEXT} +