Label

Renders an accessible label associated with controls.

Features

  • Text selection is prevented when double clicking label.
  • Supports nested controls.
  • Supports custom controls.

Install the component from your command line.

npm install @radix-ui/react-label

Import the component.

import * as Label from '@radix-ui/react-label';
export default () => <Label.Root />;

Create your styled label component.

First name
import { styled } from 'path-to/stitches.config';
import * as Label from '@radix-ui/react-label';
const StyledLabel = styled(Label.Root, {
fontSize: '16px',
fontFamily: 'system-ui',
});
export default () => <StyledLabel>First name</StyledLabel>;

Contains the content for the label.

PropTypeDefault
asenumspan
htmlForstringNo default value

Use the htmlfor attribute to connect the label with the input's id.

First name
import { styled } from 'path-to/stitches.config';
import * as Label from '@radix-ui/react-label';
const StyledLabel = styled(Label.Root, {
fontSize: '16px',
fontFamily: 'system-ui',
cursor: 'default',
});
const Input = styled('input', {});
export default () => (
<>
<StyledLabel htmlFor="firstName">First name</StyledLabel>
<Input type="text" id="firstName" css={{ ml: 10 }} />
</>
);

Add an aria-labelledby attribute to your custom controls using the useLabelContext hook to add support for label nesting.

I agree to the terms and conditions
import { styled } from 'path-to/stitches.config';
import * as Label from '@radix-ui/react-label';
import { useLabelContext } from '@radix-ui/react-label';
const StyledLabel = styled(Label.Root, {
fontSize: '16px',
fontFamily: 'system-ui',
cursor: 'default',
});
/* A custom form control you have built */
const CustomCheckbox = () => {
const id = useLabelContext();
return (
<CustomCheckboxPart aria-labelledby={id} tabIndex={0} role="checkbox" />
);
};
const CustomCheckboxPart = styled('span', {
display: 'inline-block',
verticalAlign: 'middle',
border: '1px solid black',
width: 15,
height: 15,
});
export default () => (
<StyledLabel>
<CustomCheckbox /> I agree to the terms and conditions
</StyledLabel>
);

Using this component with our primitives, will automatically get you the correct labelling using id and aria-labelledby. You can also use the provided useLabelContext hook to support this in your own controls.