Without JavaScript
Every component renders HTML that works without JavaScript, so render it on the server. JavaScript then enhances it, as govuk-frontend’s does.
How components are enhanced
Where govuk-frontend adds behaviour in JavaScript, govuk-react uses a primitive from @govuk-react/primitives. Each primitive has two halves:
- a custom element, which enhances the markup as soon as it’s defined, with or without React
- React parts over it, which add state, such as
valueandonValueChange, once React hydrates
Until the element is defined, the component shows its no-JavaScript version. For example, the accordion shows every section, and tabs show every panel.
Before React hydrates
React’s bundle defines the elements, so by default the enhancement waits for it to download. To enhance the page sooner, inline the elements’ scripts in the head. Each is small, with no imports and no React, and is defined only once, whichever runs first. React’s parts then pick up from the elements, including anything the user did before hydration.
Install the primitives, at the version govuk-react uses, and render the scripts your page needs:
import { InlineScript, accordion, tabs } from '@govuk-react/primitives/inline-script';
<head>
<InlineScript script={accordion} nonce={nonce} />
<InlineScript script={tabs} nonce={nonce} />
</head>;
Pass nonce if your Content Security Policy needs one. InlineScript isn’t a client component, so the scripts stay out of your client bundle. See inline scripts.
Islands
Components work in separate React roots, such as Astro islands, because nothing depends on React context. Where a component’s parts can render in different islands, such as tabs, pass the ids or names that a root would otherwise generate.
Checking your service
Turn JavaScript off in your browser, and check every page still works. Each example on this site has a “Without JavaScript” option that shows the component as it renders before JavaScript.