# Bringing React components to an Astro site

The toolkit ships as a static Astro site. Its header, service cards, lesson cards and contact form are built with Astro and HTML. You can edit all of them without installing React.

## Where would React help?

Suppose your existing React site has a quote calculator. A visitor changes the dimensions and the estimate updates immediately. Keep that calculator as a React component inside the Astro service page. The page title, service description and inquiry link can stay in Astro. A gallery with category filters or a multi-step project planner can follow the same pattern.

## Bring over one component

1. In your own copy of the toolkit, run `npx astro add react` and review the dependency and configuration changes.
2. Copy your calculator to `src/components/QuoteCalculator.tsx`. The example below assumes a default export. Bring over its styles and required props. If it reads from a router or shared context, pass the data as props or include its provider inside the same React component tree.
3. Import the component in the Astro page that needs it. For a calculator farther down a service page, place the component beside the pricing explanation.

```astro
---
import QuoteCalculator from '../../components/QuoteCalculator';
---

<QuoteCalculator client:visible />
```

This snippet assumes the page lives in `src/pages/services/`. Add the import to its existing frontmatter and the component to its existing layout. On a shared service template, conditionally render it for the applicable service. The calculator in this example is supplied by you.

`client:visible` starts the interactive JavaScript when the component enters the viewport. Use `client:load` for controls visitors need immediately. Components can render to HTML during the build, so move browser-only work such as reading local storage into an effect.

## Try a complete component on the sample site

After adding the React integration, save this as `src/components/AreaCalculator.tsx`. It calculates floor area from two dimensions in feet.

```tsx
import { useState } from 'react';

export default function AreaCalculator() {
  const [length, setLength] = useState('');
  const [width, setWidth] = useState('');
  const area = Number(length) * Number(width);
  const valid = Number(length) > 0 && Number(width) > 0 && Number.isFinite(area);

  return (
    <fieldset>
      <legend>Calculate project area</legend>
      <label>Length (ft) <input type="number" min="0" step="any" value={length}
        onChange={event => setLength(event.target.value)} /></label>
      <label>Width (ft) <input type="number" min="0" step="any" value={width}
        onChange={event => setWidth(event.target.value)} /></label>
      <p><output>{valid ? area.toLocaleString('en-US', {maximumFractionDigits: 2}) + ' sq ft' : 'Enter two positive dimensions.'}</output></p>
    </fieldset>
  );
}
```

In `src/pages/services/[...slug].astro`, add this import inside the existing frontmatter.

```astro
import AreaCalculator from '../../components/AreaCalculator';
```

Immediately after `<Content />`, insert the component for the site-planning service.

```astro
{entry.id === 'site-planning' && <AreaCalculator client:visible />}
```

Open `/services/site-planning/`, scroll to the calculator and enter 12 and 20. The result should read **240 sq ft**. Clear either field to return to the input instructions.

## Allow the calculator to run on Cloudflare Pages

The default `public/_headers` blocks executable scripts. A local dev preview does not apply that file. In your React-enabled copy, run `npm run build` and inspect the script elements in `dist/services/site-planning/index.html`. For the calculator example, Astro emits inline startup scripts and loads the React modules from the same origin. From the project root, print the hashes for those inline scripts:

```sh
node --input-type=module <<'JS'
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
const html = readFileSync('dist/services/site-planning/index.html', 'utf8');
for (const [, attrs, body] of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
  if (body && !attrs.includes('application/ld+json')) {
    console.log("'sha256-" + createHash('sha256').update(body).digest('base64') + "'");
  }
}
JS
```

After reviewing the scripts, replace only `script-src 'none'` in your copy of `public/_headers` with `script-src 'self'` followed by the printed quoted hashes before the semicolon. Preserve the other directives. Run `npm run qa` again. Recheck hashes when builds change or you add widgets on other routes. On your Cloudflare preview, check the console for blocked scripts and repeat the 12 × 20 keyboard test before publishing.

## Move a page and verify it

Map one existing React URL to an Astro route with the same path. Preserve its title, description, images and inquiry destination. Inventory API calls separately, especially form submissions and authenticated data. Run `npm run qa`, open the preview URL directly, refresh it, and operate the widget by keyboard. For a form, verify delivery with the existing provider.

[Astro React integration](https://docs.astro.build/en/guides/integrations-guide/react/) · [Astro migration guide for Create React App](https://docs.astro.build/en/guides/migrate-to-astro/from-create-react-app/)
