Composites and parts
Most components are made of parts, one for each element govuk-frontend renders, and a composite that renders them all for basic usage.
Composites
A composite renders the whole component, as govuk-frontend’s Nunjucks macro does. It’s called Composite, or Field for form controls:
import { InputField } from 'govuk-react/input';
<InputField name="cost" label="Cost" hint="In pounds" errorMessage="Enter a cost" prefix="£" />;
A Field renders the form group, label, hint and error message, and wires up their ids and aria-describedby. Its label, hint and errorMessage props take content only, such as text or JSX. Some composites also take their items as an array prop, as a convenience, but children are always an alternative, and recommended.
Parts
When a composite doesn’t do what you need, compose the parts yourself. They render the same markup, and you choose every id and attribute:
import { ErrorMessageComposite, FormGroup, Hint, Input, InputPrefix, InputWrapper, Label } from 'govuk-react';
<FormGroup error>
<Label htmlFor="cost">Cost</Label>
<Hint id="cost-hint">In pounds</Hint>
<ErrorMessageComposite id="cost-error">Enter a cost</ErrorMessageComposite>
<InputWrapper>
<InputPrefix>£</InputPrefix>
<Input id="cost" name="cost" error aria-describedby="cost-hint cost-error" />
</InputWrapper>
</FormGroup>;
Every element a composite renders is also a part, so you can add your own props to any of them, such as a data- attribute or an event handler.
Naming
- A multi-part component is a module of named exports, such as
DateInput.Item. Import it as a namespace:import * as DateInput from 'govuk-react/date-input'. Rootis the outermost part, and only exists when other parts sit inside it.- A component with a single part is named after itself, such as
LabelorButton. - A part that renders several elements is a composite, such as
ErrorMessageCompositeorRadios.ItemComposite.
Ids
A Field derives its ids as govuk-frontend’s macro does: the hint and error message ids come from the control’s id, which falls back to its name. To make them unique, pass id={useId()}. Grouped controls, such as Radios.Field and Checkboxes.Field, take idPrefix instead. The parts derive nothing.