Перейти к содержимому

Migrating from Create React App (CRA)

Это содержимое пока не доступно на вашем языке.

Astro’s React integration provides support for using React components inside Astro components, including entire React apps like Create React App (CRA)!

src/pages/index.astro
---
// Import your root App component
import App from '../cra-project/App.jsx';
---
<!-- Use a client directive to load your app -->
<App client:load />
See how to Build a Single Page Application (SPA) with Astro External using React Router.

Many apps will “just work” as full React apps when you add them directly to your Astro project with the React integration installed. This is a great way to get your project up and running immediately and keep your app functional while you migrate to Astro.

Over time, you can convert your structure piece-by-piece to a combination of .astro and .jsx components. You will probably discover you need fewer React components than you think!

Here are some key concepts and migration strategies to help you get started. Use the rest of our docs and our Discord community to keep going!

Key Similarities between CRA and Astro

Section titled Key Similarities between CRA and Astro

Key Differences between CRA and Astro

Section titled Key Differences between CRA and Astro

When you rebuild your CRA site in Astro, you will notice some important differences:

  • CRA is a single-page application that uses index.js as your project’s root. Astro is a multi-page site, and index.astro is your home page.

  • .astro components are not written as exported functions that return page templating. Instead, you’ll split your code into a “code fence” for your JavaScript and a body exclusively for the HTML you generate.

  • content-driven: Astro was designed to showcase your content and to allow you to opt-in to interactivity only as needed. An existing CRA app might be built for high client-side interactivity and may require advanced Astro techniques to include items that are more challenging to replicate using .astro components, such as dashboards.

Your existing app can be rendered directly inside a new Astro project, often with no changes to your app’s code.

Use the create astro command for your package manager to launch Astro’s CLI wizard and select a new “empty” Astro project.

Terminal window
npm create astro@latest

Add integrations and dependencies

Section titled Add integrations and dependencies

Add the React integration using the astro add command for your package manager. If your app uses Tailwind or MDX, you can add multiple Astro integrations using the same command:

Terminal window
npx astro add react
npx astro add react tailwind mdx

If your CRA requires any dependencies (e.g. NPM packages), then install them individually using the command line or by adding them to your new Astro project’s package.json manually and then running an install command. Note that many, but not all, React dependencies will work in Astro.

Copy your existing Create React App (CRA) project source files and folders (e.g. components, hooks, styles, etc.) into a new folder inside src/, keeping its file structure so your app will continue to work. Note that all .js file extensions must be renamed to .jsx or .tsx.

Do not include any configuration files. You will use Astro’s own astro.config.mjs, package.json, and tsconfig.json.

Move the contents of your app’s public/ folder (e.g. static assets) into Astro’s public/ folder.

  • Директорияpublic/
    • logo.png
    • favicon.ico
  • Директорияsrc/
    • Директорияcra-project/
      • App.jsx
    • Директорияpages/
      • index.astro
  • astro.config.mjs
  • package.json
  • tsconfig.json

Import your app’s root component in the frontmatter section of index.astro, then render the <App /> component in your page template:

src/pages/index.astro
---
import App from '../cra-project/App.jsx';
---
<App client:load />

See our guide for configuring Astro for more details and available options.

After adding your existing app to Astro, you will probably want to convert your app itself to Astro!

You will replicate a similar component-based design using Astro HTML templating components for your basic structure while importing and including individual React components (which may themselves be entire apps!) for islands of interactivity.

Every migration will look different and can be done incrementally without disrupting your working app. Convert individual pieces at your own pace so that more and more of your app is powered by Astro components over time.

As you convert your React app, you will decide which React components you will rewrite as Astro components. Your only restriction is that Astro components can import React components, but React components must only import other React components:

src/pages/static-components.astro
---
import MyReactComponent from '../components/MyReactComponent.jsx';
---
<html>
<body>
<h1>Use React components directly in Astro!</h1>
<MyReactComponent />
</body>
</html>

Instead of importing Astro components into React components, you can nest React components inside a single Astro component:

src/pages/nested-components.astro
---
import MyReactSidebar from '../components/MyReactSidebar.jsx';
import MyReactButton from '../components/MyReactButton.jsx';
---
<MyReactSidebar>
<p>Here is a sidebar with some text and a button.</p>
<div slot="actions">
<MyReactButton client:idle />
</div>
</MyReactSidebar>

You may find it helpful to learn about Astro islands and Astro components before restructuring your CRA as an Astro project.

Compare the following CRA component and a corresponding Astro component:

StarCount.jsx
import React, { useState, useEffect } from 'react';
import Header from './Header';
import Footer from './Footer';
const Component = () => {
const [stars, setStars] = useState(0);
const [message, setMessage] = useState('');
useEffect(() => {
const fetchData = async () => {
const res = await fetch('https://api.github.com/repos/withastro/astro');
const json = await res.json();
setStars(json.stargazers_count || 0);
setMessage(json.message);
};
fetchData();
}, []);
return (
<>
<Header />
<p style={{
backgroundColor: `#f4f4f4`,
padding: `1em 1.5em`,
textAlign: `center`,
marginBottom: `1em`
}}>Astro has {stars} 🧑‍🚀</p>
<Footer />
</>
)
};
export default Component;

Converting JSX files to .astro files

Section titled Converting JSX files to .astro files

Here are some tips for converting a CRA .js component into a .astro component:

  1. Use the returned JSX of the existing CRA component function as the basis for your HTML template.

  2. Change any CRA or JSX syntax to Astro or to HTML web standards. This includes {children} and className, for example.

  3. Move any necessary JavaScript, including import statements, into a “code fence” (---). Note: JavaScript to conditionally render content is often written inside the HTML template directly in Astro.

  4. Use Astro.props to access any additional props that were previously passed to your CRA function.

  5. Decide whether any imported components also need to be converted to Astro. You can keep them as React components for now, or forever. But, you may eventually want to convert them to .astro components, especially if they do not need to be interactive!

  6. Replace useEffect() with import statements or Astro.glob() to query your local files. Use fetch() to fetch external data.

As Astro outputs raw HTML, it is possible to write end-to-end tests using the output of the build step. Any end-to-end tests written previously might work out-of-the-box if you have been able to match the markup of your CRA site. Testing libraries such as Jest and React Testing Library can be imported and used in Astro to test your React components.

See Astro’s testing guide for more.

Reference: Convert CRA Syntax to Astro

Section titled Reference: Convert CRA Syntax to Astro

Update any file imports to reference relative file paths exactly. This can be done using import aliases, or by writing out a relative path in full.

Note that .astro and several other file types must be imported with their full file extension.

src/pages/authors/Fred.astro
---
import Card from '../../components/Card.astro';
---
<Card />

Convert any instances of {children} to an Astro <slot />. Astro does not need to receive {children} as a function prop and will automatically render child content in a <slot />.

src/components/MyComponent.astro
---
---
export default function MyComponent(props) {
return (
<div>
{props.children}
</div>
);
}
<div>
<slot />
</div>

React components that pass multiple sets of children can be migrated to an Astro component using named slots.

See more about specific <slot /> usage in Astro.

Fetching data in a Create React App component is similar to Astro, with some slight differences.

You will need to remove any instances of a side effect hook (useEffect) for either Astro.glob() or getCollection()/getEntryBySlug() to access data from other files in your project source.

To fetch remote data, use fetch().

These data requests are made in the frontmatter of the Astro component and use top-level await.

src/pages/index.astro
---
import { getCollection } from 'astro:content';
// Get all `src/content/blog/` entries
const allBlogPosts = await getCollection('blog');
// Get all `src/pages/posts/` entries
const allPosts = await Astro.glob('../pages/posts/*.md');
// Fetch remote data
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
const randomUser = data.results[0];
---

See more about local files imports with Astro.glob(), querying using the Collections API or fetching remote data.

You may need to replace any CSS-in-JS libraries (e.g. styled-components) with other available CSS options in Astro.

If necessary, convert any inline style objects (style={{ fontWeight: "bold" }}) to inline HTML style attributes (style="font-weight:bold;"). Or, use an Astro <style> tag for scoped CSS styles.

src/components/Card.astro
<div style={{backgroundColor: `#f4f4f4`, padding: `1em`}}>{message}</div>
<div style="background-color: #f4f4f4; padding: 1em;">{message}</div>

Tailwind is supported after installing the Tailwind integration. No changes to your existing Tailwind code are required!

See more about Styling in Astro.

Your CRA might “just work” in Astro! But, you may likely need to make minor adjustments to duplicate your existing app’s functionality and/or styles.

If you cannot find your answers within these docs, please visit the Astro Discord and ask questions in our support forum!

Дополнительные руководства по миграции

Внести свой вклад

Что у вас на уме?

Сообщество