Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[joy-ui][FormControl] Fix issue with the conditional setting of htmlFor and id attributes not functioning properly for form labels #40180

18 changes: 18 additions & 0 deletions packages/mui-joy/src/FormControl/FormControl.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -505,4 +505,22 @@ describe('<FormControl />', () => {
expect(getByRole('combobox')).to.have.attribute('disabled');
});
});

it('should inherit htmlFor from FormControl if htmlFor is undefined', () => {
const { getByText } = render(
<FormControl>
<FormLabel htmlFor={undefined}>label</FormLabel>
</FormControl>,
);
expect(getByText('label')).to.have.attribute('for');
});

it('should inherit id from FormControl if id is undefined', () => {
const { getByText } = render(
<FormControl>
<FormLabel id={undefined}>label</FormLabel>
</FormControl>,
);
expect(getByText('label')).to.have.attribute('id');
});
});
30 changes: 26 additions & 4 deletions packages/mui-joy/src/FormLabel/FormLabel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,16 @@ const FormLabel = React.forwardRef(function FormLabel(inProps, ref) {
name: 'JoyFormLabel',
});

const { children, component = 'label', slots = {}, slotProps = {}, ...other } = props;
const {
children,
component = 'label',
htmlFor,
id,
slots = {},
slotProps = {},
...other
} = props;

const formControl = React.useContext(FormControlContext);
const required = inProps.required ?? formControl?.required ?? false;

Expand All @@ -72,12 +81,17 @@ const FormLabel = React.forwardRef(function FormLabel(inProps, ref) {
};

const classes = useUtilityClasses();
const externalForwardedProps = { ...other, component, slots, slotProps };
const externalForwardedProps = {
...other,
component,
slots,
slotProps,
};

const [SlotRoot, rootProps] = useSlot('root', {
additionalProps: {
htmlFor: formControl?.htmlFor,
id: formControl?.labelId,
htmlFor: htmlFor ?? formControl?.htmlFor,
id: id ?? formControl?.labelId,
},
ref,
className: classes.root,
Expand Down Expand Up @@ -116,6 +130,14 @@ FormLabel.propTypes /* remove-proptypes */ = {
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* @ignore
*/
htmlFor: PropTypes.string,
/**
* @ignore
*/
id: PropTypes.string,
/**
* The asterisk is added if required=`true`
*/
Expand Down