diff --git a/.eslintrc b/.eslintrc index 7bc6ab9333b..935fa2f2343 100644 --- a/.eslintrc +++ b/.eslintrc @@ -9,7 +9,8 @@ "react-hooks/exhaustive-deps": "error", "react/no-unknown-property": ["error", {"ignore": ["meta"]}], "react-compiler/react-compiler": "error", - "local-rules/lint-markdown-code-blocks": "error" + "local-rules/lint-markdown-code-blocks": "error", + "no-trailing-spaces": "error" }, "env": { "node": true, diff --git a/src/content/blog/2023/03/16/introducing-react-dev.md b/src/content/blog/2023/03/16/introducing-react-dev.md index f971ddafadb..96d2a630da6 100644 --- a/src/content/blog/2023/03/16/introducing-react-dev.md +++ b/src/content/blog/2023/03/16/introducing-react-dev.md @@ -279,17 +279,17 @@ export default function PackingList() {

Sally Ride's Packing List

@@ -317,17 +317,17 @@ export default function PackingList() {

Sally Ride's Packing List

@@ -365,17 +365,17 @@ export default function PackingList() {

Sally Ride's Packing List

@@ -409,17 +409,17 @@ export default function PackingList() {

Sally Ride's Packing List

diff --git a/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md b/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md index c3ab47fad2b..002dae2a94c 100644 --- a/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md +++ b/src/content/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024.md @@ -49,19 +49,19 @@ We refer to this broader collection of features as simply "Actions". Actions all The `action` function can operate synchronously or asynchronously. You can define them on the client side using standard JavaScript or on the server with the [`'use server'`](/reference/rsc/use-server) directive. When using an action, React will manage the life cycle of the data submission for you, providing hooks like [`useFormStatus`](/reference/react-dom/hooks/useFormStatus), and [`useActionState`](/reference/react/useActionState) to access the current state and response of the form action. -By default, Actions are submitted within a [transition](/reference/react/useTransition), keeping the current page interactive while the action is processing. Since Actions support async functions, we've also added the ability to use `async/await` in transitions. This allows you to show pending UI with the `isPending` state of a transition when an async request like `fetch` starts, and show the pending UI all the way through the update being applied. +By default, Actions are submitted within a [transition](/reference/react/useTransition), keeping the current page interactive while the action is processing. Since Actions support async functions, we've also added the ability to use `async/await` in transitions. This allows you to show pending UI with the `isPending` state of a transition when an async request like `fetch` starts, and show the pending UI all the way through the update being applied. Alongside Actions, we're introducing a feature named [`useOptimistic`](/reference/react/useOptimistic) for managing optimistic state updates. With this hook, you can apply temporary updates that are automatically reverted once the final state commits. For Actions, this allows you to optimistically set the final state of the data on the client, assuming the submission is successful, and revert to the value for data received from the server. It works using regular `async`/`await`, so it works the same whether you're using `fetch` on the client, or a Server Action from the server. Library authors can implement custom `action={fn}` props in their own components with `useTransition`. Our intent is for libraries to adopt the Actions pattern when designing their component APIs, to provide a consistent experience for React developers. For example, if your library provides a `` component, consider also exposing a `` API, too. -While we initially focused on Server Actions for client-server data transfer, our philosophy for React is to provide the same programming model across all platforms and environments. When possible, if we introduce a feature on the client, we aim to make it also work on the server, and vice versa. This philosophy allows us to create a single set of APIs that work no matter where your app runs, making it easier to upgrade to different environments later. +While we initially focused on Server Actions for client-server data transfer, our philosophy for React is to provide the same programming model across all platforms and environments. When possible, if we introduce a feature on the client, we aim to make it also work on the server, and vice versa. This philosophy allows us to create a single set of APIs that work no matter where your app runs, making it easier to upgrade to different environments later. Actions are now available in the Canary channel and will ship in the next release of React. ## New Features in React Canary {/*new-features-in-react-canary*/} -We introduced [React Canaries](/blog/2023/05/03/react-canaries) as an option to adopt individual new stable features as soon as their design is close to final, before they’re released in a stable semver version. +We introduced [React Canaries](/blog/2023/05/03/react-canaries) as an option to adopt individual new stable features as soon as their design is close to final, before they’re released in a stable semver version. Canaries are a change to the way we develop React. Previously, features would be researched and built privately inside of Meta, so users would only see the final polished product when released to Stable. With Canaries, we’re building in public with the help of the community to finalize features we share in the React Labs blog series. This means you hear about new features sooner, as they’re being finalized instead of after they’re complete. @@ -75,7 +75,7 @@ React Server Components, Asset Loading, Document Metadata, and Actions have all - **Actions**: As shared above, we've added Actions to manage sending data from the client to the server. You can add `action` to elements like [`
`](/reference/react-dom/components/form), access the status with [`useFormStatus`](/reference/react-dom/hooks/useFormStatus), handle the result with [`useActionState`](/reference/react/useActionState), and optimistically update the UI with [`useOptimistic`](/reference/react/useOptimistic). -Since all of these features work together, it’s difficult to release them in the Stable channel individually. Releasing Actions without the complementary hooks for accessing form states would limit the practical usability of Actions. Introducing React Server Components without integrating Server Actions would complicate modifying data on the server. +Since all of these features work together, it’s difficult to release them in the Stable channel individually. Releasing Actions without the complementary hooks for accessing form states would limit the practical usability of Actions. Introducing React Server Components without integrating Server Actions would complicate modifying data on the server. Before we can release a set of features to the Stable channel, we need to ensure they work cohesively and developers have everything they need to use them in production. React Canaries allow us to develop these features individually, and release the stable APIs incrementally until the entire feature set is complete. diff --git a/src/content/blog/2024/04/25/react-19-upgrade-guide.md b/src/content/blog/2024/04/25/react-19-upgrade-guide.md index cb83a61764c..1823ebdfbd7 100644 --- a/src/content/blog/2024/04/25/react-19-upgrade-guide.md +++ b/src/content/blog/2024/04/25/react-19-upgrade-guide.md @@ -20,7 +20,7 @@ The improvements added to React 19 require some breaking changes, but we've work #### React 18.3 has also been published {/*react-18-3*/} -To help make the upgrade to React 19 easier, we've published a `react@18.3` release that is identical to 18.2 but adds warnings for deprecated APIs and other changes that are needed for React 19. +To help make the upgrade to React 19 easier, we've published a `react@18.3` release that is identical to 18.2 but adds warnings for deprecated APIs and other changes that are needed for React 19. We recommend upgrading to React 18.3 first to help identify any issues before upgrading to React 19. @@ -109,17 +109,17 @@ npx codemod@latest react/19/migration-recipe ``` This will run the following codemods from `react-codemod`: -- [`replace-reactdom-render`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-reactdom-render) +- [`replace-reactdom-render`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-reactdom-render) - [`replace-string-ref`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-string-ref) - [`replace-act-import`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-act-import) -- [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-use-form-state) +- [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-use-form-state) - [`prop-types-typescript`](https://github.com/reactjs/react-codemod#react-proptypes-to-prop-types) This does not include the TypeScript changes. See [TypeScript changes](#typescript-changes) below. -Changes that include a codemod include the command below. +Changes that include a codemod include the command below. For a list of all available codemods, see the [`react-codemod` repo](https://github.com/reactjs/react-codemod). @@ -127,7 +127,7 @@ For a list of all available codemods, see the [`react-codemod` repo](https://git ### Errors in render are not re-thrown {/*errors-in-render-are-not-re-thrown*/} -In previous versions of React, errors thrown during render were caught and rethrown. In DEV, we would also log to `console.error`, resulting in duplicate error logs. +In previous versions of React, errors thrown during render were caught and rethrown. In DEV, we would also log to `console.error`, resulting in duplicate error logs. In React 19, we've [improved how errors are handled](/blog/2024/04/25/react-19#error-handling) to reduce duplication by not re-throwing: @@ -348,7 +348,7 @@ npm install react-shallow-renderer --save-dev ##### Please reconsider shallow rendering {/*please-reconsider-shallow-rendering*/} -Shallow rendering depends on React internals and can block you from future upgrades. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro). +Shallow rendering depends on React internals and can block you from future upgrades. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro). @@ -465,7 +465,7 @@ npx codemod@latest react/19/replace-reactdom-render #### Removed: `ReactDOM.findDOMNode` {/*removed-reactdom-finddomnode*/} -`ReactDOM.findDOMNode` was [deprecated in October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html#deprecations-in-strictmode). +`ReactDOM.findDOMNode` was [deprecated in October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html#deprecations-in-strictmode). We're removing `findDOMNode` because it was a legacy escape hatch that was slow to execute, fragile to refactoring, only returned the first child, and broke abstraction levels (see more [here](https://legacy.reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage)). You can replace `ReactDOM.findDOMNode` with [DOM refs](/learn/manipulating-the-dom-with-refs): @@ -551,7 +551,7 @@ This change means Suspense fallbacks display faster, while still warming lazy re ### UMD builds removed {/*umd-builds-removed*/} -UMD was widely used in the past as a convenient way to load React without a build step. Now, there are modern alternatives for loading modules as scripts in HTML documents. Starting with React 19, React will no longer produce UMD builds to reduce the complexity of its testing and release process. +UMD was widely used in the past as a convenient way to load React without a build step. Now, there are modern alternatives for loading modules as scripts in HTML documents. Starting with React 19, React will no longer produce UMD builds to reduce the complexity of its testing and release process. To load React 19 with a script tag, we recommend using an ESM-based CDN such as [esm.sh](https://esm.sh/). @@ -569,7 +569,7 @@ This release includes changes to React internals that may impact libraries that Based on our [Versioning Policy](https://react.dev/community/versioning-policy#what-counts-as-a-breaking-change), these updates are not listed as breaking changes, and we are not including docs for how to upgrade them. The recommendation is to remove any code that depends on internals. -To reflect the impact of using internals, we have renamed the `SECRET_INTERNALS` suffix to: +To reflect the impact of using internals, we have renamed the `SECRET_INTERNALS` suffix to: `_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE` diff --git a/src/content/blog/2024/12/05/react-19.md b/src/content/blog/2024/12/05/react-19.md index 4e9aad8e829..74964645887 100644 --- a/src/content/blog/2024/12/05/react-19.md +++ b/src/content/blog/2024/12/05/react-19.md @@ -59,7 +59,7 @@ function UpdateName({}) { if (error) { setError(error); return; - } + } redirect("/path"); }; @@ -92,7 +92,7 @@ function UpdateName({}) { if (error) { setError(error); return; - } + } redirect("/path"); }) }; @@ -176,7 +176,7 @@ const [error, submitAction, isPending] = useActionState( ); ``` -`useActionState` accepts a function (the "Action"), and returns a wrapped Action to call. This works because Actions compose. When the wrapped Action is called, `useActionState` will return the last result of the Action as `data`, and the pending state of the Action as `pending`. +`useActionState` accepts a function (the "Action"), and returns a wrapped Action to call. This works because Actions compose. When the wrapped Action is called, `useActionState` will return the last result of the Action as `data`, and the pending state of the Action as `pending`. @@ -308,7 +308,7 @@ function Heading({children}) { if (children == null) { return null; } - + // This would not work with useContext // because of the early return. const theme = use(ThemeContext); @@ -330,7 +330,7 @@ We've added two new APIs to `react-dom/static` for static site generation: - [`prerender`](/reference/react-dom/static/prerender) - [`prerenderToNodeStream`](/reference/react-dom/static/prerenderToNodeStream) -These new APIs improve on `renderToString` by waiting for data to load for static HTML generation. They are designed to work with streaming environments like Node.js Streams and Web Streams. For example, in a Web Stream environment, you can prerender a React tree to static HTML with `prerender`: +These new APIs improve on `renderToString` by waiting for data to load for static HTML generation. They are designed to work with streaming environments like Node.js Streams and Web Streams. For example, in a Web Stream environment, you can prerender a React tree to static HTML with `prerender`: ```js import { prerender } from 'react-dom/static'; @@ -355,14 +355,14 @@ For more information, see [React DOM Static APIs](/reference/react-dom/static). Server Components are a new option that allows rendering components ahead of time, before bundling, in an environment separate from your client application or SSR server. This separate environment is the "server" in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server. -React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a `react-server` [export condition](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md#react-server-conditional-exports) for use in frameworks that support the [Full-stack React Architecture](/learn/creating-a-react-app#which-features-make-up-the-react-teams-full-stack-architecture-vision). +React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a `react-server` [export condition](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md#react-server-conditional-exports) for use in frameworks that support the [Full-stack React Architecture](/learn/creating-a-react-app#which-features-make-up-the-react-teams-full-stack-architecture-vision). #### How do I build support for Server Components? {/*how-do-i-build-support-for-server-components*/} -While React Server Components in React 19 are stable and will not break between minor versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x. +While React Server Components in React 19 are stable and will not break between minor versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x. To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future. @@ -497,7 +497,7 @@ function App({children}) { {children} - ); + ); } ``` @@ -521,7 +521,7 @@ We now support returning a cleanup function from `ref` callbacks: /> ``` -When the component unmounts, React will call the cleanup function returned from the `ref` callback. This works for DOM refs, refs to class components, and `useImperativeHandle`. +When the component unmounts, React will call the cleanup function returned from the `ref` callback. This works for DOM refs, refs to class components, and `useImperativeHandle`. @@ -551,7 +551,7 @@ function Search({deferredValue}) { // On initial render the value is ''. // Then a re-render is scheduled with the deferredValue. const value = useDeferredValue(deferredValue, ''); - + return ( ); @@ -564,7 +564,7 @@ For more, see [`useDeferredValue`](/reference/react/useDeferredValue). ### Support for Document Metadata {/*support-for-metadata-tags*/} -In HTML, document metadata tags like ``, `<link>`, and `<meta>` are reserved for placement in the `<head>` section of the document. In React, the component that decides what metadata is appropriate for the app may be very far from the place where you render the `<head>` or React does not render the `<head>` at all. In the past, these elements would need to be inserted manually in an effect, or by libraries like [`react-helmet`](https://github.com/nfl/react-helmet), and required careful handling when server rendering a React application. +In HTML, document metadata tags like `<title>`, `<link>`, and `<meta>` are reserved for placement in the `<head>` section of the document. In React, the component that decides what metadata is appropriate for the app may be very far from the place where you render the `<head>` or React does not render the `<head>` at all. In the past, these elements would need to be inserted manually in an effect, or by libraries like [`react-helmet`](https://github.com/nfl/react-helmet), and required careful handling when server rendering a React application. In React 19, we're adding support for rendering document metadata tags in components natively: @@ -726,7 +726,7 @@ In React 19, unexpected tags in the `<head>` and `<body>` will be skipped over, ### Better error reporting {/*error-handling*/} -We improved error handling in React 19 to remove duplication and provide options for handling caught and uncaught errors. For example, when there's an error in render caught by an Error Boundary, previously React would throw the error twice (once for the original error, then again after failing to automatically recover), and then call `console.error` with info about where the error occurred. +We improved error handling in React 19 to remove duplication and provide options for handling caught and uncaught errors. For example, when there's an error in render caught by an Error Boundary, previously React would throw the error twice (once for the original error, then again after failing to automatically recover), and then call `console.error` with info about where the error occurred. This resulted in three errors for every caught error: diff --git a/src/content/blog/2025/02/14/sunsetting-create-react-app.md b/src/content/blog/2025/02/14/sunsetting-create-react-app.md index 6f3e95d8111..45c0090d51b 100644 --- a/src/content/blog/2025/02/14/sunsetting-create-react-app.md +++ b/src/content/blog/2025/02/14/sunsetting-create-react-app.md @@ -11,7 +11,7 @@ February 14, 2025 by [Matt Carroll](https://twitter.com/mattcarrollcode) and [Ri <Intro> -Today, we’re deprecating [Create React App](https://create-react-app.dev/) for new apps, and encouraging existing apps to migrate to a [framework](#how-to-migrate-to-a-framework), or to [migrate to a build tool](#how-to-migrate-to-a-build-tool) like Vite, Parcel, or RSBuild. +Today, we’re deprecating [Create React App](https://create-react-app.dev/) for new apps, and encouraging existing apps to migrate to a [framework](#how-to-migrate-to-a-framework), or to [migrate to a build tool](#how-to-migrate-to-a-build-tool) like Vite, Parcel, or RSBuild. We’re also providing docs for when a framework isn’t a good fit for your project, you want to build your own framework, or you just want to learn how React works by [building a React app from scratch](/learn/build-a-react-app-from-scratch). @@ -75,7 +75,7 @@ To help get started with Vite, Parcel or Rsbuild, we've added new docs for [Buil #### Do I need a framework? {/*do-i-need-a-framework*/} -Most apps would benefit from a framework, but there are valid cases to build a React app from scratch. A good rule of thumb is if your app needs routing, you would probably benefit from a framework. +Most apps would benefit from a framework, but there are valid cases to build a React app from scratch. A good rule of thumb is if your app needs routing, you would probably benefit from a framework. Just like Svelte has Sveltekit, Vue has Nuxt, and Solid has SolidStart, [React recommends using a framework](#why-we-recommend-frameworks) that fully integrates routing into features like data-fetching and code-splitting out of the box. This avoids the pain of needing to write your own complex configurations and essentially build a framework yourself. diff --git a/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md b/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md index dc049c78c67..70e5c2e658b 100644 --- a/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md +++ b/src/content/blog/2025/12/11/denial-of-service-and-source-code-exposure-in-react-server-components.md @@ -176,7 +176,7 @@ The patches published today prevent stringifying the Server Function source code Secrets hardcoded in source code may be exposed, but runtime secrets such as `process.env.SECRET` are not affected. -The scope of the exposed code is limited to the code inside the Server Function, which may include other functions depending on the amount of inlining your bundler provides. +The scope of the exposed code is limited to the code inside the Server Function, which may include other functions depending on the amount of inlining your bundler provides. Always verify against production bundles. diff --git a/src/content/community/conferences.md b/src/content/community/conferences.md index ada81a60b65..2079cdd656b 100644 --- a/src/content/community/conferences.md +++ b/src/content/community/conferences.md @@ -219,7 +219,7 @@ May 15 - 16, 2024. In-person in Henderson, NV, USA + remote [Website](https://conf.react.dev) - [Twitter](https://twitter.com/reactjs) ### React Native Connection 2024 {/*react-native-connection-2024*/} -April 23, 2024. In-person in Paris, France +April 23, 2024. In-person in Paris, France [Website](https://reactnativeconnection.io/) - [Twitter](https://twitter.com/ReactNativeConn) @@ -261,7 +261,7 @@ October 20 & 23, 2023. In-person in London, UK + remote first interactivity (hyb ### React Brussels 2023 {/*react-brussels-2023*/} October 13th 2023. In-person in Brussels, Belgium + Remote (hybrid) -[Website](https://www.react.brussels/) - [Twitter](https://twitter.com/BrusselsReact) - [Videos](https://www.youtube.com/playlist?list=PL53Z0yyYnpWh85KeMomUoVz8_brrmh_aC) +[Website](https://www.react.brussels/) - [Twitter](https://twitter.com/BrusselsReact) - [Videos](https://www.youtube.com/playlist?list=PL53Z0yyYnpWh85KeMomUoVz8_brrmh_aC) ### React India 2023 {/*react-india-2023*/} October 5 - 7, 2023. In-person in Goa, India (hybrid event) + Oct 3 2023 - remote day @@ -284,7 +284,7 @@ September 28 - 30, 2023. Alicante, Spain [Website](https://reactalicante.es/) - [Twitter](https://twitter.com/reactalicante) ### RedwoodJS Conference 2023 {/*redwoodjs-conference-2023*/} -September 26 - 29, 2023. Grants Pass, Oregon + remote (hybrid event) +September 26 - 29, 2023. Grants Pass, Oregon + remote (hybrid event) [Website](https://www.redwoodjsconf.com/) - [Twitter](https://twitter.com/redwoodjs) diff --git a/src/content/community/translations.md b/src/content/community/translations.md index 4c07e6a1ea2..fd49bd3e97a 100644 --- a/src/content/community/translations.md +++ b/src/content/community/translations.md @@ -28,7 +28,7 @@ For the progress of each translation, see: [Is React Translated Yet?](https://tr ## How to contribute {/*how-to-contribute*/} -You can contribute to the translation efforts! +You can contribute to the translation efforts! The community conducts the translation work for the React docs on each language-specific fork of react.dev. Typical translation work involves directly translating a Markdown file and creating a pull request. Click the "contribute" link above to the GitHub repository for your language, and follow the instructions there to help with the translation effort. diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md index 8a2142cf91d..182ad54bb1a 100644 --- a/src/content/learn/build-a-react-app-from-scratch.md +++ b/src/content/learn/build-a-react-app-from-scratch.md @@ -12,7 +12,7 @@ If your app has constraints not well-served by existing frameworks, you prefer t #### Consider using a framework {/*consider-using-a-framework*/} -Starting from scratch is an easy way to get started using React, but a major tradeoff to be aware of is that going this route is often the same as building your own adhoc framework. As your requirements evolve, you may need to solve more framework-like problems that our recommended frameworks already have well developed and supported solutions for. +Starting from scratch is an easy way to get started using React, but a major tradeoff to be aware of is that going this route is often the same as building your own adhoc framework. As your requirements evolve, you may need to solve more framework-like problems that our recommended frameworks already have well developed and supported solutions for. For example, if in the future your app needs support for server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC), you will have to implement those on your own. Similarly, future React features that require integrating at the framework level will have to be implemented on your own if you want to use them. @@ -132,12 +132,12 @@ Since the build tool you select only supports single page apps (SPAs), you'll ne * **React Server Components (RSC)** lets you mix build-time, server-only, and interactive components in a single React tree. RSC can improve performance, but it currently requires deep expertise to set up and maintain. See [Parcel's RSC examples](https://github.com/parcel-bundler/rsc-examples). -Your rendering strategies need to integrate with your router so apps built with your framework can choose the rendering strategy on a per-route level. This will enable different rendering strategies without having to rewrite your whole app. For example, the landing page for your app might benefit from being statically generated (SSG), while a page with a content feed might perform best with server-side rendering. +Your rendering strategies need to integrate with your router so apps built with your framework can choose the rendering strategy on a per-route level. This will enable different rendering strategies without having to rewrite your whole app. For example, the landing page for your app might benefit from being statically generated (SSG), while a page with a content feed might perform best with server-side rendering. Using the right rendering strategy for the right routes can decrease the time it takes for the first byte of content to be loaded ([Time to First Byte](https://web.dev/articles/ttfb)), the first piece of content to render ([First Contentful Paint](https://web.dev/articles/fcp)), and the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)). ### And more... {/*and-more*/} -These are just a few examples of the features a new app will need to consider when building from scratch. Many limitations you'll hit can be difficult to solve as each problem is interconnected with the others and can require deep expertise in problem areas you may not be familiar with. +These are just a few examples of the features a new app will need to consider when building from scratch. Many limitations you'll hit can be difficult to solve as each problem is interconnected with the others and can require deep expertise in problem areas you may not be familiar with. -If you don't want to solve these problems on your own, you can [get started with a framework](/learn/creating-a-react-app) that provides these features out of the box. +If you don't want to solve these problems on your own, you can [get started with a framework](/learn/creating-a-react-app) that provides these features out of the box. diff --git a/src/content/learn/choosing-the-state-structure.md b/src/content/learn/choosing-the-state-structure.md index f6ed669ab44..2533a53d85d 100644 --- a/src/content/learn/choosing-the-state-structure.md +++ b/src/content/learn/choosing-the-state-structure.md @@ -458,7 +458,7 @@ export default function Menu() { return ( <> - <h2>What's your travel snack?</h2> + <h2>What's your travel snack?</h2> <ul> {items.map((item, index) => ( <li key={item.id}> @@ -804,7 +804,7 @@ export const initialTravelPlan = { }, { id: 48, title: 'Green Hill', - childPlaces: [] + childPlaces: [] }] }] }; @@ -882,7 +882,7 @@ export const initialTravelPlan = { id: 2, title: 'Africa', childIds: [3, 4, 5, 6 , 7, 8, 9] - }, + }, 3: { id: 3, title: 'Botswana', @@ -902,7 +902,7 @@ export const initialTravelPlan = { id: 6, title: 'Madagascar', childIds: [] - }, + }, 7: { id: 7, title: 'Morocco', @@ -921,7 +921,7 @@ export const initialTravelPlan = { 10: { id: 10, title: 'Americas', - childIds: [11, 12, 13, 14, 15, 16, 17, 18], + childIds: [11, 12, 13, 14, 15, 16, 17, 18], }, 11: { id: 11, @@ -937,7 +937,7 @@ export const initialTravelPlan = { id: 13, title: 'Barbados', childIds: [] - }, + }, 14: { id: 14, title: 'Canada', @@ -966,7 +966,7 @@ export const initialTravelPlan = { 19: { id: 19, title: 'Asia', - childIds: [20, 21, 22, 23, 24, 25], + childIds: [20, 21, 22, 23, 24, 25], }, 20: { id: 20, @@ -1001,7 +1001,7 @@ export const initialTravelPlan = { 26: { id: 26, title: 'Europe', - childIds: [27, 28, 29, 30, 31, 32, 33], + childIds: [27, 28, 29, 30, 31, 32, 33], }, 27: { id: 27, @@ -1041,7 +1041,7 @@ export const initialTravelPlan = { 34: { id: 34, title: 'Oceania', - childIds: [35, 36, 37, 38, 39, 40, 41], + childIds: [35, 36, 37, 38, 39, 40, 41], }, 35: { id: 35, @@ -1218,7 +1218,7 @@ export const initialTravelPlan = { id: 2, title: 'Africa', childIds: [3, 4, 5, 6 , 7, 8, 9] - }, + }, 3: { id: 3, title: 'Botswana', @@ -1238,7 +1238,7 @@ export const initialTravelPlan = { id: 6, title: 'Madagascar', childIds: [] - }, + }, 7: { id: 7, title: 'Morocco', @@ -1257,7 +1257,7 @@ export const initialTravelPlan = { 10: { id: 10, title: 'Americas', - childIds: [11, 12, 13, 14, 15, 16, 17, 18], + childIds: [11, 12, 13, 14, 15, 16, 17, 18], }, 11: { id: 11, @@ -1273,7 +1273,7 @@ export const initialTravelPlan = { id: 13, title: 'Barbados', childIds: [] - }, + }, 14: { id: 14, title: 'Canada', @@ -1302,7 +1302,7 @@ export const initialTravelPlan = { 19: { id: 19, title: 'Asia', - childIds: [20, 21, 22, 23, 24, 25], + childIds: [20, 21, 22, 23, 24, 25], }, 20: { id: 20, @@ -1337,7 +1337,7 @@ export const initialTravelPlan = { 26: { id: 26, title: 'Europe', - childIds: [27, 28, 29, 30, 31, 32, 33], + childIds: [27, 28, 29, 30, 31, 32, 33], }, 27: { id: 27, @@ -1377,7 +1377,7 @@ export const initialTravelPlan = { 34: { id: 34, title: 'Oceania', - childIds: [35, 36, 37, 38, 39, 40, 41], + childIds: [35, 36, 37, 38, 39, 40, 41], }, 35: { id: 35, @@ -1557,7 +1557,7 @@ export const initialTravelPlan = { id: 2, title: 'Africa', childIds: [3, 4, 5, 6 , 7, 8, 9] - }, + }, 3: { id: 3, title: 'Botswana', @@ -1577,7 +1577,7 @@ export const initialTravelPlan = { id: 6, title: 'Madagascar', childIds: [] - }, + }, 7: { id: 7, title: 'Morocco', @@ -1596,7 +1596,7 @@ export const initialTravelPlan = { 10: { id: 10, title: 'Americas', - childIds: [11, 12, 13, 14, 15, 16, 17, 18], + childIds: [11, 12, 13, 14, 15, 16, 17, 18], }, 11: { id: 11, @@ -1612,7 +1612,7 @@ export const initialTravelPlan = { id: 13, title: 'Barbados', childIds: [] - }, + }, 14: { id: 14, title: 'Canada', @@ -1641,7 +1641,7 @@ export const initialTravelPlan = { 19: { id: 19, title: 'Asia', - childIds: [20, 21, 22, 23, 24, 25,], + childIds: [20, 21, 22, 23, 24, 25,], }, 20: { id: 20, @@ -1676,7 +1676,7 @@ export const initialTravelPlan = { 26: { id: 26, title: 'Europe', - childIds: [27, 28, 29, 30, 31, 32, 33], + childIds: [27, 28, 29, 30, 31, 32, 33], }, 27: { id: 27, @@ -1716,7 +1716,7 @@ export const initialTravelPlan = { 34: { id: 34, title: 'Oceania', - childIds: [35, 36, 37, 38, 39, 40, 41], + childIds: [35, 36, 37, 38, 39, 40, 41], }, 35: { id: 35, @@ -1821,7 +1821,7 @@ Sometimes, you can also reduce state nesting by moving some of the nested state <Recap> -* If two state variables always update together, consider merging them into one. +* If two state variables always update together, consider merging them into one. * Choose your state variables carefully to avoid creating "impossible" states. * Structure your state in a way that reduces the chances that you'll make a mistake updating it. * Avoid redundant and duplicate state so that you don't need to keep it in sync. @@ -2060,7 +2060,7 @@ export default function TravelPlan() { } return ( - <> + <> <AddItem onAddItem={handleAddItem} /> @@ -2195,7 +2195,7 @@ export default function TravelPlan() { } return ( - <> + <> <AddItem onAddItem={handleAddItem} /> @@ -2348,7 +2348,7 @@ export default function Letter({ isHighlighted ? 'highlighted' : '' } onFocus={() => { - onHover(letter); + onHover(letter); }} onPointerMove={() => { onHover(letter); @@ -2457,7 +2457,7 @@ export default function Letter({ isHighlighted ? 'highlighted' : '' } onFocus={() => { - onHover(letter.id); + onHover(letter.id); }} onPointerMove={() => { onHover(letter.id); diff --git a/src/content/learn/conditional-rendering.md b/src/content/learn/conditional-rendering.md index 95be5d2e018..7a75fe021d8 100644 --- a/src/content/learn/conditional-rendering.md +++ b/src/content/learn/conditional-rendering.md @@ -32,17 +32,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -80,17 +80,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -132,17 +132,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -236,17 +236,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -290,17 +290,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -371,17 +371,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -417,17 +417,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -474,17 +474,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -512,17 +512,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - isPacked={true} - name="Space suit" + <Item + isPacked={true} + name="Space suit" /> - <Item - isPacked={true} - name="Helmet with a golden leaf" + <Item + isPacked={true} + name="Helmet with a golden leaf" /> - <Item - isPacked={false} - name="Photo of Tam" + <Item + isPacked={false} + name="Photo of Tam" /> </ul> </section> @@ -560,17 +560,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - importance={9} - name="Space suit" + <Item + importance={9} + name="Space suit" /> - <Item - importance={0} - name="Helmet with a golden leaf" + <Item + importance={0} + name="Helmet with a golden leaf" /> - <Item - importance={6} - name="Photo of Tam" + <Item + importance={6} + name="Photo of Tam" /> </ul> </section> @@ -604,17 +604,17 @@ export default function PackingList() { <section> <h1>Sally Ride's Packing List</h1> <ul> - <Item - importance={9} - name="Space suit" + <Item + importance={9} + name="Space suit" /> - <Item - importance={0} - name="Helmet with a golden leaf" + <Item + importance={0} + name="Helmet with a golden leaf" /> - <Item - importance={6} - name="Photo of Tam" + <Item + importance={6} + name="Photo of Tam" /> </ul> </section> diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md index a65b59f6efb..fef66838e72 100644 --- a/src/content/learn/creating-a-react-app.md +++ b/src/content/learn/creating-a-react-app.md @@ -104,7 +104,7 @@ Server Components and Suspense are React features rather than Next.js features. If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, there are other options available for starting a React project from scratch. -Starting from scratch gives you more flexibility, but does require that you make choices on which tools to use for routing, data fetching, and other common usage patterns. It's a lot like building your own framework, instead of using a framework that already exists. The [frameworks we recommend](#full-stack-frameworks) have built-in solutions for these problems. +Starting from scratch gives you more flexibility, but does require that you make choices on which tools to use for routing, data fetching, and other common usage patterns. It's a lot like building your own framework, instead of using a framework that already exists. The [frameworks we recommend](#full-stack-frameworks) have built-in solutions for these problems. If you want to build your own solutions, see our guide to [build a React app from Scratch](/learn/build-a-react-app-from-scratch) for instructions on how to set up a new React project starting with a build tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/). diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index 339f04223cf..8e0f0ff7dec 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -526,9 +526,9 @@ Read **[Keeping Components Pure](/learn/keeping-components-pure)** to learn how ## Your UI as a tree {/*your-ui-as-a-tree*/} -React uses trees to model the relationships between components and modules. +React uses trees to model the relationships between components and modules. -A React render tree is a representation of the parent and child relationship between components. +A React render tree is a representation of the parent and child relationship between components. <Diagram name="generic_render_tree" height={250} width={500} alt="A tree graph with five nodes, with each node representing a component. The root node is located at the top the tree graph and is labelled 'Root Component'. It has two arrows extending down to two nodes labelled 'Component A' and 'Component C'. Each of the arrows is labelled with 'renders'. 'Component A' has a single 'renders' arrow to a node labelled 'Component B'. 'Component C' has a single 'renders' arrow to a node labelled 'Component D'."> @@ -538,7 +538,7 @@ An example React render tree. Components near the top of the tree, near the root component, are considered top-level components. Components with no child components are leaf components. This categorization of components is useful for understanding data flow and rendering performance. -Modelling the relationship between JavaScript modules is another useful way to understand your app. We refer to it as a module dependency tree. +Modelling the relationship between JavaScript modules is another useful way to understand your app. We refer to it as a module dependency tree. <Diagram name="generic_dependency_tree" height={250} width={500} alt="A tree graph with five nodes. Each node represents a JavaScript module. The top-most node is labelled 'RootModule.js'. It has three arrows extending to the nodes: 'ModuleA.js', 'ModuleB.js', and 'ModuleC.js'. Each arrow is labelled as 'imports'. 'ModuleC.js' node has a single 'imports' arrow that points to a node labelled 'ModuleD.js'."> @@ -546,7 +546,7 @@ An example module dependency tree. </Diagram> -A dependency tree is often used by build tools to bundle all the relevant JavaScript code for the client to download and render. A large bundle size regresses user experience for React apps. Understanding the module dependency tree is helpful to debug such issues. +A dependency tree is often used by build tools to bundle all the relevant JavaScript code for the client to download and render. A large bundle size regresses user experience for React apps. Understanding the module dependency tree is helpful to debug such issues. <LearnMore path="/learn/understanding-your-ui-as-a-tree"> diff --git a/src/content/learn/editor-setup.md b/src/content/learn/editor-setup.md index 7ad7ee2763b..fb469d3761c 100644 --- a/src/content/learn/editor-setup.md +++ b/src/content/learn/editor-setup.md @@ -31,7 +31,7 @@ Some editors come with these features built in, but others might require adding ### Linting {/*linting*/} -Code linters find problems in your code as you write, helping you fix them early. [ESLint](https://eslint.org/) is a popular, open source linter for JavaScript. +Code linters find problems in your code as you write, helping you fix them early. [ESLint](https://eslint.org/) is a popular, open source linter for JavaScript. * [Install ESLint with the recommended configuration for React](https://www.npmjs.com/package/eslint-config-react-app) (be sure you have [Node installed!](https://nodejs.org/en/download/current/)) * [Integrate ESLint in VSCode with the official extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) diff --git a/src/content/learn/escape-hatches.md b/src/content/learn/escape-hatches.md index ab5f666ad8c..cbaef8bb36f 100644 --- a/src/content/learn/escape-hatches.md +++ b/src/content/learn/escape-hatches.md @@ -227,7 +227,7 @@ function Form() { } ``` -However, you *do* need Effects to synchronize with external systems. +However, you *do* need Effects to synchronize with external systems. <LearnMore path="/learn/you-might-not-need-an-effect"> @@ -382,7 +382,7 @@ export default function App() { <hr /> <ChatRoom roomId={roomId} - theme={isDark ? 'dark' : 'light'} + theme={isDark ? 'dark' : 'light'} /> </> ); @@ -515,7 +515,7 @@ export default function App() { <hr /> <ChatRoom roomId={roomId} - theme={isDark ? 'dark' : 'light'} + theme={isDark ? 'dark' : 'light'} /> </> ); diff --git a/src/content/learn/importing-and-exporting-components.md b/src/content/learn/importing-and-exporting-components.md index b458ef402a1..01cb037082b 100644 --- a/src/content/learn/importing-and-exporting-components.md +++ b/src/content/learn/importing-and-exporting-components.md @@ -118,7 +118,7 @@ Notice how this example is broken down into two component files now: You may encounter files that leave off the `.js` file extension like so: -```js +```js import Gallery from './Gallery'; ``` diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md index fafd488e33b..4eec0720fd9 100644 --- a/src/content/learn/keeping-components-pure.md +++ b/src/content/learn/keeping-components-pure.md @@ -27,13 +27,13 @@ You might already be familiar with one example of pure functions: formulas in ma Consider this math formula: <Math><MathI>y</MathI> = 2<MathI>x</MathI></Math>. -If <Math><MathI>x</MathI> = 2</Math> then <Math><MathI>y</MathI> = 4</Math>. Always. +If <Math><MathI>x</MathI> = 2</Math> then <Math><MathI>y</MathI> = 4</Math>. Always. -If <Math><MathI>x</MathI> = 3</Math> then <Math><MathI>y</MathI> = 6</Math>. Always. +If <Math><MathI>x</MathI> = 3</Math> then <Math><MathI>y</MathI> = 6</Math>. Always. -If <Math><MathI>x</MathI> = 3</Math>, <MathI>y</MathI> won't sometimes be <Math>9</Math> or <Math>–1</Math> or <Math>2.5</Math> depending on the time of day or the state of the stock market. +If <Math><MathI>x</MathI> = 3</Math>, <MathI>y</MathI> won't sometimes be <Math>9</Math> or <Math>–1</Math> or <Math>2.5</Math> depending on the time of day or the state of the stock market. -If <Math><MathI>y</MathI> = 2<MathI>x</MathI></Math> and <Math><MathI>x</MathI> = 3</Math>, <MathI>y</MathI> will _always_ be <Math>6</Math>. +If <Math><MathI>y</MathI> = 2<MathI>x</MathI></Math> and <Math><MathI>x</MathI> = 3</Math>, <MathI>y</MathI> will _always_ be <Math>6</Math>. If we made this into a JavaScript function, it would look like this: @@ -52,7 +52,7 @@ React is designed around this concept. **React assumes that every component you ```js src/App.js function Recipe({ drinkers }) { return ( - <ol> + <ol> <li>Boil {drinkers} cups of water.</li> <li>Add {drinkers} spoons of tea and {0.5 * drinkers} spoons of spice.</li> <li>Add {0.5 * drinkers} cups of milk to boil and sugar to taste.</li> @@ -75,11 +75,11 @@ export default function App() { </Sandpack> -When you pass `drinkers={2}` to `Recipe`, it will return JSX containing `2 cups of water`. Always. +When you pass `drinkers={2}` to `Recipe`, it will return JSX containing `2 cups of water`. Always. If you pass `drinkers={4}`, it will return JSX containing `4 cups of water`. Always. -Just like a math formula. +Just like a math formula. You could think of your components as recipes: if you follow them and don't introduce new ingredients during the cooking process, you will get the same dish every time. That "dish" is the JSX that the component serves to React to [render.](/learn/render-and-commit) @@ -217,7 +217,7 @@ Every new React feature we're building takes advantage of purity. From data fetc * A component must be pure, meaning: * **It minds its own business.** It should not change any objects or variables that existed before rendering. - * **Same inputs, same output.** Given the same inputs, a component should always return the same JSX. + * **Same inputs, same output.** Given the same inputs, a component should always return the same JSX. * Rendering can happen at any time, so components should not depend on each others' rendering sequence. * You should not mutate any of the inputs that your components use for rendering. That includes props, state, and context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects. * Strive to express your component's logic in the JSX you return. When you need to "change things", you'll usually want to do it in an event handler. As a last resort, you can `useEffect`. @@ -226,7 +226,7 @@ Every new React feature we're building takes advantage of purity. From data fetc </Recap> - + <Challenges> #### Fix a broken clock {/*fix-a-broken-clock*/} diff --git a/src/content/learn/lifecycle-of-reactive-effects.md b/src/content/learn/lifecycle-of-reactive-effects.md index 72a2e77559f..608db09a00e 100644 --- a/src/content/learn/lifecycle-of-reactive-effects.md +++ b/src/content/learn/lifecycle-of-reactive-effects.md @@ -293,7 +293,7 @@ You might be wondering how React knew that your Effect needed to re-synchronize ```js {1,3,8} function ChatRoom({ roomId }) { // The roomId prop may change over time useEffect(() => { - const connection = createConnection(serverUrl, roomId); // This Effect reads roomId + const connection = createConnection(serverUrl, roomId); // This Effect reads roomId connection.connect(); return () => { connection.disconnect(); @@ -969,7 +969,7 @@ export default function App() { <label> <input type="checkbox" checked={canMove} - onChange={e => setCanMove(e.target.checked)} + onChange={e => setCanMove(e.target.checked)} /> The dot is allowed to move </label> @@ -1027,7 +1027,7 @@ export default function App() { <label> <input type="checkbox" checked={canMove} - onChange={e => setCanMove(e.target.checked)} + onChange={e => setCanMove(e.target.checked)} /> The dot is allowed to move </label> @@ -1083,7 +1083,7 @@ export default function App() { <label> <input type="checkbox" checked={canMove} - onChange={e => setCanMove(e.target.checked)} + onChange={e => setCanMove(e.target.checked)} /> The dot is allowed to move </label> @@ -1155,7 +1155,7 @@ export default function App() { <label> <input type="checkbox" checked={canMove} - onChange={e => setCanMove(e.target.checked)} + onChange={e => setCanMove(e.target.checked)} /> The dot is allowed to move </label> @@ -1220,7 +1220,7 @@ export default function App() { <label> <input type="checkbox" checked={canMove} - onChange={e => setCanMove(e.target.checked)} + onChange={e => setCanMove(e.target.checked)} /> The dot is allowed to move </label> @@ -1279,7 +1279,7 @@ export default function App() { <label> <input type="checkbox" checked={canMove} - onChange={e => setCanMove(e.target.checked)} + onChange={e => setCanMove(e.target.checked)} /> The dot is allowed to move </label> @@ -1711,7 +1711,7 @@ async function fetchPlanets() { name: 'Venus' }, { id: 'mars', - name: 'Mars' + name: 'Mars' }]); }, 1000); }); @@ -1735,7 +1735,7 @@ async function fetchPlaces(planetId) { name: 'Spain' }, { id: 'vietnam', - name: 'Vietnam' + name: 'Vietnam' }]); } else if (planetId === 'venus') { resolve([{ @@ -1746,7 +1746,7 @@ async function fetchPlaces(planetId) { name: 'Diana Chasma' }, { id: 'kumsong-vallis', - name: 'Kŭmsŏng Vallis' + name: 'Kŭmsŏng Vallis' }]); } else if (planetId === 'mars') { resolve([{ @@ -1879,7 +1879,7 @@ async function fetchPlanets() { name: 'Venus' }, { id: 'mars', - name: 'Mars' + name: 'Mars' }]); }, 1000); }); @@ -1903,7 +1903,7 @@ async function fetchPlaces(planetId) { name: 'Spain' }, { id: 'vietnam', - name: 'Vietnam' + name: 'Vietnam' }]); } else if (planetId === 'venus') { resolve([{ @@ -1914,7 +1914,7 @@ async function fetchPlaces(planetId) { name: 'Diana Chasma' }, { id: 'kumsong-vallis', - name: 'Kŭmsŏng Vallis' + name: 'Kŭmsŏng Vallis' }]); } else if (planetId === 'mars') { resolve([{ @@ -2042,7 +2042,7 @@ async function fetchPlanets() { name: 'Venus' }, { id: 'mars', - name: 'Mars' + name: 'Mars' }]); }, 1000); }); @@ -2066,7 +2066,7 @@ async function fetchPlaces(planetId) { name: 'Spain' }, { id: 'vietnam', - name: 'Vietnam' + name: 'Vietnam' }]); } else if (planetId === 'venus') { resolve([{ @@ -2077,7 +2077,7 @@ async function fetchPlaces(planetId) { name: 'Diana Chasma' }, { id: 'kumsong-vallis', - name: 'Kŭmsŏng Vallis' + name: 'Kŭmsŏng Vallis' }]); } else if (planetId === 'mars') { resolve([{ diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md index e81678c8e2e..d9879b32e95 100644 --- a/src/content/learn/passing-data-deeply-with-context.md +++ b/src/content/learn/passing-data-deeply-with-context.md @@ -857,7 +857,7 @@ If neither of these approaches works well for you, consider context. * **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value. * **Routing:** Most routing solutions use context internally to hold the current route. This is how every link "knows" whether it's active or not. If you build your own router, you might want to do it too. * **Managing state:** As your app grows, you might end up with a lot of state closer to the top of your app. Many distant components below may want to change it. It is common to [use a reducer together with context](/learn/scaling-up-with-reducer-and-context) to manage complex state and pass it down to distant components without too much hassle. - + Context is not limited to static values. If you pass a different value on the next render, React will update all the components reading it below! This is why context is often used in combination with state. In general, if some information is needed by distant components in different parts of the tree, it's a good indication that context will help you. @@ -963,27 +963,27 @@ export const places = [{ description: 'The tradition of choosing bright colors for houses began in the late 20th century.', imageId: 'K9HVAGH' }, { - id: 1, + id: 1, name: 'Rainbow Village in Taichung, Taiwan', description: 'To save the houses from demolition, Huang Yung-Fu, a local resident, painted all 1,200 of them in 1924.', imageId: '9EAYZrt' }, { - id: 2, + id: 2, name: 'Macromural de Pachuca, Mexico', description: 'One of the largest murals in the world covering homes in a hillside neighborhood.', imageId: 'DgXHVwu' }, { - id: 3, + id: 3, name: 'Selarón Staircase in Rio de Janeiro, Brazil', description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people."', imageId: 'aeO3rpI' }, { - id: 4, + id: 4, name: 'Burano, Italy', description: 'The houses are painted following a specific color system dating back to 16th century.', imageId: 'kxsph5C' }, { - id: 5, + id: 5, name: 'Chefchaouen, Marocco', description: 'There are a few theories on why the houses are painted blue, including that the color repels mosquitos or that it symbolizes sky and heaven.', imageId: 'rTqKo46' @@ -1007,9 +1007,9 @@ export function getImageUrl(place) { ```css ul { list-style-type: none; padding: 0px 10px; } -li { - margin-bottom: 10px; - display: grid; +li { + margin-bottom: 10px; + display: grid; grid-template-columns: auto 1fr; gap: 20px; align-items: center; @@ -1102,27 +1102,27 @@ export const places = [{ description: 'The tradition of choosing bright colors for houses began in the late 20th century.', imageId: 'K9HVAGH' }, { - id: 1, + id: 1, name: 'Rainbow Village in Taichung, Taiwan', description: 'To save the houses from demolition, Huang Yung-Fu, a local resident, painted all 1,200 of them in 1924.', imageId: '9EAYZrt' }, { - id: 2, + id: 2, name: 'Macromural de Pachuca, Mexico', description: 'One of the largest murals in the world covering homes in a hillside neighborhood.', imageId: 'DgXHVwu' }, { - id: 3, + id: 3, name: 'Selarón Staircase in Rio de Janeiro, Brazil', description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people".', imageId: 'aeO3rpI' }, { - id: 4, + id: 4, name: 'Burano, Italy', description: 'The houses are painted following a specific color system dating back to 16th century.', imageId: 'kxsph5C' }, { - id: 5, + id: 5, name: 'Chefchaouen, Marocco', description: 'There are a few theories on why the houses are painted blue, including that the color repels mosquitos or that it symbolizes sky and heaven.', imageId: 'rTqKo46' @@ -1146,9 +1146,9 @@ export function getImageUrl(place) { ```css ul { list-style-type: none; padding: 0px 10px; } -li { - margin-bottom: 10px; - display: grid; +li { + margin-bottom: 10px; + display: grid; grid-template-columns: auto 1fr; gap: 20px; align-items: center; diff --git a/src/content/learn/passing-props-to-a-component.md b/src/content/learn/passing-props-to-a-component.md index aae682d14d2..fad10fe2adf 100644 --- a/src/content/learn/passing-props-to-a-component.md +++ b/src/content/learn/passing-props-to-a-component.md @@ -126,21 +126,21 @@ export default function Profile() { <div> <Avatar size={100} - person={{ - name: 'Katsuko Saruhashi', + person={{ + name: 'Katsuko Saruhashi', imageId: 'YfeOqp2' }} /> <Avatar size={80} person={{ - name: 'Aklilu Lemma', + name: 'Aklilu Lemma', imageId: 'OKS67lh' }} /> <Avatar size={50} - person={{ + person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }} @@ -291,7 +291,7 @@ export default function Profile() { <Card> <Avatar size={100} - person={{ + person={{ name: 'Katsuko Saruhashi', imageId: 'YfeOqp2' }} @@ -453,11 +453,11 @@ export default function Gallery() { /> <ul> <li> - <b>Profession: </b> + <b>Profession: </b> physicist and chemist </li> <li> - <b>Awards: 4 </b> + <b>Awards: 4 </b> (Nobel Prize in Physics, Nobel Prize in Chemistry, Davy Medal, Matteucci Medal) </li> <li> @@ -477,11 +477,11 @@ export default function Gallery() { /> <ul> <li> - <b>Profession: </b> + <b>Profession: </b> geochemist </li> <li> - <b>Awards: 2 </b> + <b>Awards: 2 </b> (Miyake Prize for geochemistry, Tanaka Prize) </li> <li> @@ -758,8 +758,8 @@ export default function Profile() { return ( <Avatar size={40} - person={{ - name: 'Gregorio Y. Zara', + person={{ + name: 'Gregorio Y. Zara', imageId: '7vQD0fP' }} /> @@ -814,15 +814,15 @@ export default function Profile() { <> <Avatar size={40} - person={{ - name: 'Gregorio Y. Zara', + person={{ + name: 'Gregorio Y. Zara', imageId: '7vQD0fP' }} /> <Avatar size={120} - person={{ - name: 'Gregorio Y. Zara', + person={{ + name: 'Gregorio Y. Zara', imageId: '7vQD0fP' }} /> @@ -878,22 +878,22 @@ export default function Profile() { <> <Avatar size={40} - person={{ - name: 'Gregorio Y. Zara', + person={{ + name: 'Gregorio Y. Zara', imageId: '7vQD0fP' }} /> <Avatar size={70} - person={{ - name: 'Gregorio Y. Zara', + person={{ + name: 'Gregorio Y. Zara', imageId: '7vQD0fP' }} /> <Avatar size={120} - person={{ - name: 'Gregorio Y. Zara', + person={{ + name: 'Gregorio Y. Zara', imageId: '7vQD0fP' }} /> diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md index 041fae35508..4a2427c19fb 100644 --- a/src/content/learn/preserving-and-resetting-state.md +++ b/src/content/learn/preserving-and-resetting-state.md @@ -86,7 +86,7 @@ label { </Sandpack> -Here's how these look as a tree: +Here's how these look as a tree: <DiagramGroup> @@ -186,7 +186,7 @@ export default function App() { return ( <div> <Counter /> - {showB && <Counter />} + {showB && <Counter />} <label> <input type="checkbox" @@ -288,9 +288,9 @@ export default function App() { return ( <div> {isFancy ? ( - <Counter isFancy={true} /> + <Counter isFancy={true} /> ) : ( - <Counter isFancy={false} /> + <Counter isFancy={false} /> )} <label> <input @@ -496,9 +496,9 @@ export default function App() { return ( <div> {isPaused ? ( - <p>See you later!</p> + <p>See you later!</p> ) : ( - <Counter /> + <Counter /> )} <label> <input @@ -596,7 +596,7 @@ export default function App() { <div> {isFancy ? ( <div> - <Counter isFancy={true} /> + <Counter isFancy={true} /> </div> ) : ( <section> @@ -1431,7 +1431,7 @@ export default function App() { if (reverse) { return ( <> - <Field label="Last name" /> + <Field label="Last name" /> <Field label="First name" /> {checkbox} </> @@ -1439,11 +1439,11 @@ export default function App() { } else { return ( <> - <Field label="First name" /> + <Field label="First name" /> <Field label="Last name" /> {checkbox} </> - ); + ); } } @@ -1493,7 +1493,7 @@ export default function App() { if (reverse) { return ( <> - <Field key="lastName" label="Last name" /> + <Field key="lastName" label="Last name" /> <Field key="firstName" label="First name" /> {checkbox} </> @@ -1501,11 +1501,11 @@ export default function App() { } else { return ( <> - <Field key="firstName" label="First name" /> + <Field key="firstName" label="First name" /> <Field key="lastName" label="Last name" /> {checkbox} </> - ); + ); } } diff --git a/src/content/learn/queueing-a-series-of-state-updates.md b/src/content/learn/queueing-a-series-of-state-updates.md index 41de6529a6d..b3be278cf4d 100644 --- a/src/content/learn/queueing-a-series-of-state-updates.md +++ b/src/content/learn/queueing-a-series-of-state-updates.md @@ -177,7 +177,7 @@ During the next render, React goes through the state queue: | "replace with `5`" | `0` (unused) | `5` | | `n => n + 1` | `5` | `5 + 1 = 6` | -React stores `6` as the final result and returns it from `useState`. +React stores `6` as the final result and returns it from `useState`. <Note> @@ -305,7 +305,7 @@ export default function RequestTracker() { Completed: {completed} </h3> <button onClick={handleClick}> - Buy + Buy </button> </> ); @@ -349,7 +349,7 @@ export default function RequestTracker() { Completed: {completed} </h3> <button onClick={handleClick}> - Buy + Buy </button> </> ); diff --git a/src/content/learn/referencing-values-with-refs.md b/src/content/learn/referencing-values-with-refs.md index 4386e2bdc44..657d3ddcb00 100644 --- a/src/content/learn/referencing-values-with-refs.md +++ b/src/content/learn/referencing-values-with-refs.md @@ -34,7 +34,7 @@ const ref = useRef(0); `useRef` returns an object like this: ```js -{ +{ current: 0 // The value you passed to useRef } ``` diff --git a/src/content/learn/removing-effect-dependencies.md b/src/content/learn/removing-effect-dependencies.md index 61eb2e8d6c9..0b69cfa64f4 100644 --- a/src/content/learn/removing-effect-dependencies.md +++ b/src/content/learn/removing-effect-dependencies.md @@ -411,7 +411,7 @@ function Form() { function handleSubmit() { setSubmitted(true); - } + } // ... } @@ -429,7 +429,7 @@ function Form() { // ✅ Good: Event-specific logic is called from event handlers post('/api/register'); showNotification('Successfully registered!', theme); - } + } // ... } @@ -878,7 +878,7 @@ const options2 = { serverUrl: 'https://localhost:1234', roomId: 'music' }; console.log(Object.is(options1, options2)); // false ``` -**Object and function dependencies can make your Effect re-synchronize more often than you need.** +**Object and function dependencies can make your Effect re-synchronize more often than you need.** This is why, whenever possible, you should try to avoid objects and functions as your Effect's dependencies. Instead, try moving them outside the component, inside the Effect, or extracting primitive values out of them. diff --git a/src/content/learn/render-and-commit.md b/src/content/learn/render-and-commit.md index f9b05e185a8..d7d8f301eee 100644 --- a/src/content/learn/render-and-commit.md +++ b/src/content/learn/render-and-commit.md @@ -124,7 +124,7 @@ img { margin: 0 10px 10px 0; } </Sandpack> -* **During the initial render,** React will [create the DOM nodes](https://developer.mozilla.org/docs/Web/API/Document/createElement) for `<section>`, `<h1>`, and three `<img>` tags. +* **During the initial render,** React will [create the DOM nodes](https://developer.mozilla.org/docs/Web/API/Document/createElement) for `<section>`, `<h1>`, and three `<img>` tags. * **During a re-render,** React will calculate which of their properties, if any, have changed since the previous render. It won't do anything with that information until the next step, the commit phase. <Pitfall> diff --git a/src/content/learn/rendering-lists.md b/src/content/learn/rendering-lists.md index 32f81c44707..9cec4b17ae5 100644 --- a/src/content/learn/rendering-lists.md +++ b/src/content/learn/rendering-lists.md @@ -115,7 +115,7 @@ const people = [{ }, { id: 3, name: 'Percy Lavon Julian', - profession: 'chemist', + profession: 'chemist', }, { id: 4, name: 'Subrahmanyan Chandrasekhar', @@ -232,9 +232,9 @@ export function getImageUrl(person) { ```css ul { list-style-type: none; padding: 0px 10px; } -li { - margin-bottom: 10px; - display: grid; +li { + margin-bottom: 10px; + display: grid; grid-template-columns: auto 1fr; gap: 20px; align-items: center; @@ -362,9 +362,9 @@ export function getImageUrl(person) { ```css ul { list-style-type: none; padding: 0px 10px; } -li { - margin-bottom: 10px; - display: grid; +li { + margin-bottom: 10px; + display: grid; grid-template-columns: auto 1fr; gap: 20px; align-items: center; diff --git a/src/content/learn/responding-to-events.md b/src/content/learn/responding-to-events.md index 78474217c40..1fb554c5eee 100644 --- a/src/content/learn/responding-to-events.md +++ b/src/content/learn/responding-to-events.md @@ -169,7 +169,7 @@ This lets these two buttons show different messages. Try changing the messages p ### Passing event handlers as props {/*passing-event-handlers-as-props*/} -Often you'll want the parent component to specify a child's event handler. Consider buttons: depending on where you're using a `Button` component, you might want to execute a different function—perhaps one plays a movie and another uploads an image. +Often you'll want the parent component to specify a child's event handler. Consider buttons: depending on where you're using a `Button` component, you might want to execute a different function—perhaps one plays a movie and another uploads an image. To do this, pass a prop the component receives from its parent as the event handler like so: @@ -313,11 +313,11 @@ button { margin-right: 10px; } </Sandpack> Notice how the `App` component does not need to know *what* `Toolbar` will do with `onPlayMovie` or `onUploadImage`. That's an implementation detail of the `Toolbar`. Here, `Toolbar` passes them down as `onClick` handlers to its `Button`s, but it could later also trigger them on a keyboard shortcut. Naming props after app-specific interactions like `onPlayMovie` gives you the flexibility to change how they're used later. - + <Note> Make sure that you use the appropriate HTML tags for your event handlers. For example, to handle clicks, use [`<button onClick={handleClick}>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) instead of `<div onClick={handleClick}>`. Using a real browser `<button>` enables built-in browser behaviors like keyboard navigation. If you don't like the default browser styling of a button and want to make it look more like a link or a different UI element, you can achieve it with CSS. [Learn more about writing accessible markup.](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML) - + </Note> ## Event propagation {/*event-propagation*/} @@ -411,7 +411,7 @@ button { margin: 5px; } When you click on a button: -1. React calls the `onClick` handler passed to `<button>`. +1. React calls the `onClick` handler passed to `<button>`. 2. That handler, defined in `Button`, does the following: * Calls `e.stopPropagation()`, preventing the event from bubbling further. * Calls the `onClick` function, which is a prop passed from the `Toolbar` component. @@ -433,10 +433,10 @@ In rare cases, you might need to catch all events on child elements, *even if th </div> ``` -Each event propagates in three phases: +Each event propagates in three phases: 1. It travels down, calling all `onClickCapture` handlers. -2. It runs the clicked element's `onClick` handler. +2. It runs the clicked element's `onClick` handler. 3. It travels upwards, calling all `onClick` handlers. Capture events are useful for code like routers or analytics, but you probably won't use them in app code. diff --git a/src/content/learn/scaling-up-with-reducer-and-context.md b/src/content/learn/scaling-up-with-reducer-and-context.md index fe1762d8ed8..01483bebf48 100644 --- a/src/content/learn/scaling-up-with-reducer-and-context.md +++ b/src/content/learn/scaling-up-with-reducer-and-context.md @@ -801,7 +801,7 @@ export default function AddTask() { type: 'added', id: nextId++, text: text, - }); + }); }}>Add</button> </> ); @@ -1025,7 +1025,7 @@ export default function AddTask() { type: 'added', id: nextId++, text: text, - }); + }); }}>Add</button> </> ); @@ -1244,7 +1244,7 @@ export default function AddTask() { type: 'added', id: nextId++, text: text, - }); + }); }}>Add</button> </> ); diff --git a/src/content/learn/sharing-state-between-components.md b/src/content/learn/sharing-state-between-components.md index 52eaf28f85d..2fbef891801 100644 --- a/src/content/learn/sharing-state-between-components.md +++ b/src/content/learn/sharing-state-between-components.md @@ -323,7 +323,7 @@ To see what this feels like in practice with a few more components, read [Thinki #### Synced inputs {/*synced-inputs*/} -These two inputs are independent. Make them stay in sync: editing one input should update the other input with the same text, and vice versa. +These two inputs are independent. Make them stay in sync: editing one input should update the other input with the same text, and vice versa. <Hint> @@ -571,7 +571,7 @@ function SearchBar({ query, onChange }) { function List({ items }) { return ( <table> - <tbody> + <tbody> {items.map(food => ( <tr key={food.id}> <td>{food.name}</td> diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md index 0efe1191db0..55b9717afd6 100644 --- a/src/content/learn/state-a-components-memory.md +++ b/src/content/learn/state-a-components-memory.md @@ -40,14 +40,14 @@ export default function Gallery() { Next </button> <h2> - <i>{sculpture.name} </i> + <i>{sculpture.name} </i> by {sculpture.artist} </h2> - <h3> + <h3> ({index + 1} of {sculptureList.length}) </h3> - <img - src={sculpture.url} + <img + src={sculpture.url} alt={sculpture.alt} /> <p> @@ -64,7 +64,7 @@ export const sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -220,14 +220,14 @@ export default function Gallery() { Next </button> <h2> - <i>{sculpture.name} </i> + <i>{sculpture.name} </i> by {sculpture.artist} </h2> - <h3> + <h3> ({index + 1} of {sculptureList.length}) </h3> - <img - src={sculpture.url} + <img + src={sculpture.url} alt={sculpture.alt} /> <p> @@ -244,7 +244,7 @@ export const sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -361,7 +361,7 @@ The convention is to name this pair like `const [something, setSomething]`. You </Note> -The only argument to `useState` is the **initial value** of your state variable. In this example, the `index`'s initial value is set to `0` with `useState(0)`. +The only argument to `useState` is the **initial value** of your state variable. In this example, the `index`'s initial value is set to `0` with `useState(0)`. Every time your component renders, `useState` gives you an array containing two values: @@ -408,18 +408,18 @@ export default function Gallery() { Next </button> <h2> - <i>{sculpture.name} </i> + <i>{sculpture.name} </i> by {sculpture.artist} </h2> - <h3> + <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} - <img - src={sculpture.url} + <img + src={sculpture.url} alt={sculpture.alt} /> </> @@ -433,7 +433,7 @@ export const sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -629,7 +629,7 @@ let sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -773,18 +773,18 @@ export default function Gallery() { Next </button> <h2> - <i>{sculpture.name} </i> + <i>{sculpture.name} </i> by {sculpture.artist} </h2> - <h3> + <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} - <img - src={sculpture.url} + <img + src={sculpture.url} alt={sculpture.alt} /> </section> @@ -798,7 +798,7 @@ export const sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -944,18 +944,18 @@ export default function Gallery() { Next </button> <h2> - <i>{sculpture.name} </i> + <i>{sculpture.name} </i> by {sculpture.artist} </h2> - <h3> + <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} - <img - src={sculpture.url} + <img + src={sculpture.url} alt={sculpture.alt} /> </> @@ -969,7 +969,7 @@ export const sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -1106,18 +1106,18 @@ export default function Gallery() { Next </button> <h2> - <i>{sculpture.name} </i> + <i>{sculpture.name} </i> by {sculpture.artist} </h2> - <h3> + <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} - <img - src={sculpture.url} + <img + src={sculpture.url} alt={sculpture.alt} /> </> @@ -1131,7 +1131,7 @@ export const sculptureList = [{ artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', - alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' + alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', @@ -1266,7 +1266,7 @@ export default function Form() { } ``` -```css +```css h1 { margin-top: 10px; } ``` @@ -1317,7 +1317,7 @@ export default function Form() { } ``` -```css +```css h1 { margin-top: 10px; } ``` @@ -1446,7 +1446,7 @@ export default function FeedbackForm() { Try moving the second `useState` call after the `if` condition and notice how this breaks it again. -If your linter is [configured for React](/learn/editor-setup#linting), you should see a lint error when you make a mistake like this. If you don't see an error when you try the faulty code locally, you need to set up linting for your project. +If your linter is [configured for React](/learn/editor-setup#linting), you should see a lint error when you make a mistake like this. If you don't see an error when you try the faulty code locally, you need to set up linting for your project. </Solution> diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md index 216a381b53e..70a94d64794 100644 --- a/src/content/learn/thinking-in-react.md +++ b/src/content/learn/thinking-in-react.md @@ -37,7 +37,7 @@ Start by drawing boxes around every component and subcomponent in the mockup and Depending on your background, you can think about splitting up a design into components in different ways: -* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns), that is, a component should ideally only be concerned with one thing. If it ends up growing, it should be decomposed into smaller subcomponents. +* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns), that is, a component should ideally only be concerned with one thing. If it ends up growing, it should be decomposed into smaller subcomponents. * **CSS**--consider what you would make class selectors for. (However, components are a bit less granular.) * **Design**--consider how you would organize the design's layers. @@ -228,7 +228,7 @@ What's left is probably state. Let's go through them one by one again: -1. The original list of products is **passed in as props, so it's not state.** +1. The original list of products is **passed in as props, so it's not state.** 2. The search text seems to be state since it changes over time and can't be computed from anything. 3. The value of the checkbox seems to be state since it changes over time and can't be computed from anything. 4. The filtered list of products **isn't state because it can be computed** by taking the original list of products and filtering it according to the search text and value of the checkbox. @@ -266,29 +266,29 @@ In the previous step, you found two pieces of state in this application: the sea Now let's run through our strategy for them: 1. **Identify components that use state:** - * `ProductTable` needs to filter the product list based on that state (search text and checkbox value). + * `ProductTable` needs to filter the product list based on that state (search text and checkbox value). * `SearchBar` needs to display that state (search text and checkbox value). 2. **Find their common parent:** The first parent component both components share is `FilterableProductTable`. 3. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`. -So the state values will live in `FilterableProductTable`. +So the state values will live in `FilterableProductTable`. Add state to the component with the [`useState()` Hook.](/reference/react/useState) Hooks are special functions that let you "hook into" React. Add two state variables at the top of `FilterableProductTable` and specify their initial state: ```js function FilterableProductTable({ products }) { const [filterText, setFilterText] = useState(''); - const [inStockOnly, setInStockOnly] = useState(false); + const [inStockOnly, setInStockOnly] = useState(false); ``` Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as props: ```js <div> - <SearchBar - filterText={filterText} + <SearchBar + filterText={filterText} inStockOnly={inStockOnly} /> - <ProductTable + <ProductTable products={products} filterText={filterText} inStockOnly={inStockOnly} /> @@ -308,10 +308,10 @@ function FilterableProductTable({ products }) { return ( <div> - <SearchBar - filterText={filterText} + <SearchBar + filterText={filterText} inStockOnly={inStockOnly} /> - <ProductTable + <ProductTable products={products} filterText={filterText} inStockOnly={inStockOnly} /> @@ -389,13 +389,13 @@ function ProductTable({ products, filterText, inStockOnly }) { function SearchBar({ filterText, inStockOnly }) { return ( <form> - <input - type="text" - value={filterText} + <input + type="text" + value={filterText} placeholder="Search..."/> <label> - <input - type="checkbox" + <input + type="checkbox" checked={inStockOnly} /> {' '} Only show products in stock @@ -451,9 +451,9 @@ In the sandbox above, `ProductTable` and `SearchBar` read the `filterText` and ` function SearchBar({ filterText, inStockOnly }) { return ( <form> - <input - type="text" - value={filterText} + <input + type="text" + value={filterText} placeholder="Search..."/> ``` @@ -462,7 +462,7 @@ However, you haven't added any code to respond to the user actions like typing y ## Step 5: Add inverse data flow {/*step-5-add-inverse-data-flow*/} -Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`. +Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`. React makes this data flow explicit, but it requires a little more typing than two-way data binding. If you try to type or check the box in the example above, you'll see that React ignores your input. This is intentional. By writing `<input value={filterText} />`, you've set the `value` prop of the `input` to always be equal to the `filterText` state passed in from `FilterableProductTable`. Since `filterText` state is never set, the input never changes. @@ -475,8 +475,8 @@ function FilterableProductTable({ products }) { return ( <div> - <SearchBar - filterText={filterText} + <SearchBar + filterText={filterText} inStockOnly={inStockOnly} onFilterTextChange={setFilterText} onInStockOnlyChange={setInStockOnly} /> @@ -519,13 +519,13 @@ function FilterableProductTable({ products }) { return ( <div> - <SearchBar - filterText={filterText} - inStockOnly={inStockOnly} - onFilterTextChange={setFilterText} + <SearchBar + filterText={filterText} + inStockOnly={inStockOnly} + onFilterTextChange={setFilterText} onInStockOnlyChange={setInStockOnly} /> - <ProductTable - products={products} + <ProductTable + products={products} filterText={filterText} inStockOnly={inStockOnly} /> </div> @@ -607,14 +607,14 @@ function SearchBar({ }) { return ( <form> - <input - type="text" - value={filterText} placeholder="Search..." + <input + type="text" + value={filterText} placeholder="Search..." onChange={(e) => onFilterTextChange(e.target.value)} /> <label> - <input - type="checkbox" - checked={inStockOnly} + <input + type="checkbox" + checked={inStockOnly} onChange={(e) => onInStockOnlyChange(e.target.checked)} /> {' '} Only show products in stock diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md index 115c2a9a5e9..d09d484844d 100644 --- a/src/content/learn/tutorial-tic-tac-toe.md +++ b/src/content/learn/tutorial-tic-tac-toe.md @@ -337,7 +337,7 @@ import './styles.css'; import App from './App'; ``` -Lines 1-5 bring all the necessary pieces together: +Lines 1-5 bring all the necessary pieces together: * React * React's library to talk to web browsers (React DOM) @@ -551,7 +551,7 @@ export default function Board() { } ``` -Note how unlike the browser `div`s, your own components `Board` and `Square` must start with a capital letter. +Note how unlike the browser `div`s, your own components `Board` and `Square` must start with a capital letter. Let's take a look: @@ -1094,7 +1094,7 @@ function Square({ value, onSquareClick }) { } ``` -Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name `handleClick`. To connect `onSquareClick` to `handleClick` you'll pass a function to the `onSquareClick` prop of the first `Square` component: +Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name `handleClick`. To connect `onSquareClick` to `handleClick` you'll pass a function to the `onSquareClick` prop of the first `Square` component: ```js {7} export default function Board() { @@ -2073,12 +2073,12 @@ export default function Game() { } ``` -You can see what your code should look like below. Note that you should see an error in the developer tools console that says: +You can see what your code should look like below. Note that you should see an error in the developer tools console that says: <ConsoleBlock level="warning"> Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `Game`. </ConsoleBlock> - + You'll fix this error in the next section. <Sandpack> diff --git a/src/content/learn/updating-objects-in-state.md b/src/content/learn/updating-objects-in-state.md index ca658514507..1fc37e3925d 100644 --- a/src/content/learn/updating-objects-in-state.md +++ b/src/content/learn/updating-objects-in-state.md @@ -199,7 +199,7 @@ setPosition({ Mutation is only a problem when you change *existing* objects that are already in state. Mutating an object you've just created is okay because *no other code references it yet.* Changing it isn't going to accidentally impact something that depends on it. This is called a "local mutation". You can even do local mutation [while rendering.](/learn/keeping-components-pure#local-mutation-your-components-little-secret) Very convenient and completely okay! -</DeepDive> +</DeepDive> ## Copying objects with the spread syntax {/*copying-objects-with-the-spread-syntax*/} @@ -296,7 +296,7 @@ setPerson({ }); ``` -Now the form works! +Now the form works! Notice how you didn't declare a separate state variable for each input field. For large forms, keeping all data grouped in an object is very convenient--as long as you update it correctly! @@ -373,7 +373,7 @@ input { margin-left: 5px; margin-bottom: 5px; } </Sandpack> -Note that the `...` spread syntax is "shallow"--it only copies things one level deep. This makes it fast, but it also means that if you want to update a nested property, you'll have to use it more than once. +Note that the `...` spread syntax is "shallow"--it only copies things one level deep. This makes it fast, but it also means that if you want to update a nested property, you'll have to use it more than once. <DeepDive> @@ -579,8 +579,8 @@ export default function Form() { <br /> (located in {person.artwork.city}) </p> - <img - src={person.artwork.image} + <img + src={person.artwork.image} alt={person.artwork.title} /> </> @@ -650,7 +650,7 @@ let obj3 = { If you were to mutate `obj3.artwork.city`, it would affect both `obj2.artwork.city` and `obj1.city`. This is because `obj3.artwork`, `obj2.artwork`, and `obj1` are the same object. This is difficult to see when you think of objects as "nested". Instead, they are separate objects "pointing" at each other with properties. -</DeepDive> +</DeepDive> ### Write concise update logic with Immer {/*write-concise-update-logic-with-immer*/} @@ -755,8 +755,8 @@ export default function Form() { <br /> (located in {person.artwork.city}) </p> - <img - src={person.artwork.image} + <img + src={person.artwork.image} alt={person.artwork.title} /> </> diff --git a/src/content/learn/writing-markup-with-jsx.md b/src/content/learn/writing-markup-with-jsx.md index 62670150aca..301800be4da 100644 --- a/src/content/learn/writing-markup-with-jsx.md +++ b/src/content/learn/writing-markup-with-jsx.md @@ -70,9 +70,9 @@ Suppose that you have some (perfectly valid) HTML: ```html <h1>Hedy Lamarr's Todos</h1> -<img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" +<img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" class="photo" > <ul> @@ -102,9 +102,9 @@ export default function TodoList() { return ( // This doesn't quite work! <h1>Hedy Lamarr's Todos</h1> - <img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" + <img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" class="photo" > <ul> @@ -141,9 +141,9 @@ For example, you can use a `<div>`: ```js {1,11} <div> <h1>Hedy Lamarr's Todos</h1> - <img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" + <img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" class="photo" > <ul> @@ -158,9 +158,9 @@ If you don't want to add an extra `<div>` to your markup, you can write `<>` and ```js {1,11} <> <h1>Hedy Lamarr's Todos</h1> - <img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" + <img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" class="photo" > <ul> @@ -187,9 +187,9 @@ This is how Hedy Lamarr's image and list items look closed: ```js {2-6,8-10} <> - <img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" + <img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" class="photo" /> <ul> @@ -207,9 +207,9 @@ JSX turns into JavaScript and attributes written in JSX become keys of JavaScrip This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of `stroke-width` you use `strokeWidth`. Since `class` is a reserved word, in React you write `className` instead, named after the [corresponding DOM property](https://developer.mozilla.org/en-US/docs/Web/API/Element/className): ```js {4} -<img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" +<img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" className="photo" /> ``` @@ -235,10 +235,10 @@ export default function TodoList() { return ( <> <h1>Hedy Lamarr's Todos</h1> - <img - src="https://i.imgur.com/yXOvdOSs.jpg" - alt="Hedy Lamarr" - className="photo" + <img + src="https://i.imgur.com/yXOvdOSs.jpg" + alt="Hedy Lamarr" + className="photo" /> <ul> <li>Invent new traffic lights</li> diff --git a/src/content/learn/your-first-component.md b/src/content/learn/your-first-component.md index 1c38fa65528..55e0f797a10 100644 --- a/src/content/learn/your-first-component.md +++ b/src/content/learn/your-first-component.md @@ -341,9 +341,9 @@ Or by wrapping the returned JSX markup in parentheses that open right after `ret ```js export default function Profile() { return ( - <img - src="https://i.imgur.com/jA8hHMpm.jpg" - alt="Katsuko Saruhashi" + <img + src="https://i.imgur.com/jA8hHMpm.jpg" + alt="Katsuko Saruhashi" /> ); } diff --git a/src/content/reference/dev-tools/react-performance-tracks.md b/src/content/reference/dev-tools/react-performance-tracks.md index dc2912da21f..d4757b9ec9e 100644 --- a/src/content/reference/dev-tools/react-performance-tracks.md +++ b/src/content/reference/dev-tools/react-performance-tracks.md @@ -138,7 +138,7 @@ In development builds, when you click on a component render entry, you can inspe #### Server Requests {/*server-requests*/} -The Server Requests track visualized all Promises that eventually end up in a React Server Component. This includes any `async` operations like calling `fetch` or async Node.js file operations. +The Server Requests track visualized all Promises that eventually end up in a React Server Component. This includes any `async` operations like calling `fetch` or async Node.js file operations. React will try to combine Promises that are started from inside third-party code into a single span representing the the duration of the entire operation blocking 1st party code. For example, a third party library method called `getUser` that calls `fetch` internally multiple times will be represented as a single span called `getUser`, instead of showing multiple `fetch` spans. diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md index 7f6434b9866..c42f2fabfc5 100644 --- a/src/content/reference/react-dom/client/createRoot.md +++ b/src/content/reference/react-dom/client/createRoot.md @@ -91,7 +91,7 @@ React will display `<App />` in the `root`, and take over managing the DOM insid * If you call `render` on the same root more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same root again is similar to calling the [`set` function](/reference/react/useState#setstate) on the root component: React avoids unnecessary DOM updates. * Although rendering is synchronous once it starts, `root.render(...)` is not. This means code after `root.render()` may run before any effects (`useLayoutEffect`, `useEffect`) of that specific render are fired. This is usually fine and rarely needs adjustment. In rare cases where effect timing matters, you can wrap `root.render(...)` in [`flushSync`](https://react.dev/reference/react-dom/flushSync) to ensure the initial render runs fully synchronously. - + ```js const root = createRoot(document.getElementById('root')); root.render(<App />); @@ -113,7 +113,7 @@ An app fully built with React will usually not have any calls to `root.unmount`. This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions. -Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. +Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. #### Parameters {/*root-unmount-parameters*/} @@ -197,7 +197,7 @@ function Counter() { </Sandpack> -**If your app is fully built with React, you shouldn't need to create any more roots, or to call [`root.render`](#root-render) again.** +**If your app is fully built with React, you shouldn't need to create any more roots, or to call [`root.render`](#root-render) again.** From this point on, React will manage the DOM of your entire app. To add more components, [nest them inside the `App` component.](/learn/importing-and-exporting-components) When you need to update the UI, each of your components can do this by [using state.](/reference/react/useState) When you need to display extra content like a modal or a tooltip outside the DOM node, [render it with a portal.](/reference/react-dom/createPortal) @@ -249,11 +249,11 @@ import { createRoot } from 'react-dom/client'; import { Comments, Navigation } from './Components.js'; const navDomNode = document.getElementById('navigation'); -const navRoot = createRoot(navDomNode); +const navRoot = createRoot(navDomNode); navRoot.render(<Navigation />); const commentDomNode = document.getElementById('comments'); -const commentRoot = createRoot(commentDomNode); +const commentRoot = createRoot(commentDomNode); commentRoot.render(<Comments />); ``` @@ -303,7 +303,7 @@ You could also create a new DOM node with [`document.createElement()`](https://d ```js const domNode = document.createElement('div'); -const root = createRoot(domNode); +const root = createRoot(domNode); root.render(<Comment />); document.body.appendChild(domNode); // You can add it anywhere in the document ``` @@ -508,7 +508,7 @@ To fix, pass the root options to `createRoot(...)`, not `root.render(...)`: root.render(App, {onUncaughtError}); // ✅ Correct: pass options to createRoot. -const root = createRoot(container, {onUncaughtError}); +const root = createRoot(container, {onUncaughtError}); root.render(<App />); ``` diff --git a/src/content/reference/react-dom/components/common.md b/src/content/reference/react-dom/components/common.md index f6e73b7c8bc..beb62e8aa13 100644 --- a/src/content/reference/react-dom/components/common.md +++ b/src/content/reference/react-dom/components/common.md @@ -84,11 +84,11 @@ These standard DOM props are also supported for all built-in components: * `onCutCapture`: A version of `onCut` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events) * `onDoubleClick`: A [`MouseEvent` handler](#mouseevent-handler) function. Fires when the user clicks twice. Corresponds to the browser [`dblclick` event.](https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event) * `onDoubleClickCapture`: A version of `onDoubleClick` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events) -* [`onDrag`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/drag_event): A [`DragEvent` handler](#dragevent-handler) function. Fires while the user is dragging something. +* [`onDrag`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/drag_event): A [`DragEvent` handler](#dragevent-handler) function. Fires while the user is dragging something. * `onDragCapture`: A version of `onDrag` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events) -* [`onDragEnd`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragend_event): A [`DragEvent` handler](#dragevent-handler) function. Fires when the user stops dragging something. +* [`onDragEnd`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragend_event): A [`DragEvent` handler](#dragevent-handler) function. Fires when the user stops dragging something. * `onDragEndCapture`: A version of `onDragEnd` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events) -* [`onDragEnter`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragenter_event): A [`DragEvent` handler](#dragevent-handler) function. Fires when the dragged content enters a valid drop target. +* [`onDragEnter`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragenter_event): A [`DragEvent` handler](#dragevent-handler) function. Fires when the dragged content enters a valid drop target. * `onDragEnterCapture`: A version of `onDragEnter` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events) * [`onDragOver`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragover_event): A [`DragEvent` handler](#dragevent-handler) function. Fires on a valid drop target while the dragged content is dragged over it. You must call `e.preventDefault()` here to allow dropping. * `onDragOverCapture`: A version of `onDragOver` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events) @@ -302,7 +302,7 @@ Some React events do not map directly to the browser's native events. For exampl React event objects implement some of the standard [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) properties: -* [`bubbles`](https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles): A boolean. Returns whether the event bubbles through the DOM. +* [`bubbles`](https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles): A boolean. Returns whether the event bubbles through the DOM. * [`cancelable`](https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable): A boolean. Returns whether the event can be canceled. * [`currentTarget`](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget): A DOM node. Returns the node to which the current handler is attached in the React tree. * [`defaultPrevented`](https://developer.mozilla.org/en-US/docs/Web/API/Event/defaultPrevented): A boolean. Returns whether `preventDefault` was called. @@ -662,7 +662,7 @@ An event handler type for [touch events.](https://developer.mozilla.org/en-US/do * [`shiftKey`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/shiftKey) * [`touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) * [`targetTouches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/targetTouches) - + It also includes the inherited [`UIEvent`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) properties: * [`detail`](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail) diff --git a/src/content/reference/react-dom/components/index.md b/src/content/reference/react-dom/components/index.md index 586663398c6..3a23dc11c32 100644 --- a/src/content/reference/react-dom/components/index.md +++ b/src/content/reference/react-dom/components/index.md @@ -205,7 +205,7 @@ root.render(<App />); export class MyElement extends HTMLElement { constructor() { super(); - // The value here will be overwritten by React + // The value here will be overwritten by React // when initialized as an element this.value = undefined; } diff --git a/src/content/reference/react-dom/components/input.md b/src/content/reference/react-dom/components/input.md index 17232ac1d07..37ff14d9876 100644 --- a/src/content/reference/react-dom/components/input.md +++ b/src/content/reference/react-dom/components/input.md @@ -212,7 +212,7 @@ export default function MyForm() { type="radio" name="myRadio" value="option2" - defaultChecked={true} + defaultChecked={true} /> Option 2 </label> diff --git a/src/content/reference/react-dom/components/link.md b/src/content/reference/react-dom/components/link.md index de7bec3cb9d..6d374807cae 100644 --- a/src/content/reference/react-dom/components/link.md +++ b/src/content/reference/react-dom/components/link.md @@ -151,7 +151,7 @@ export default function SiteMapPage() { ### Controlling stylesheet precedence {/*controlling-stylesheet-precedence*/} -Stylesheets can conflict with each other, and when they do, the browser goes with the one that comes later in the document. React lets you control the order of stylesheets with the `precedence` prop. In this example, three components render stylesheets, and the ones with the same precedence are grouped together in the `<head>`. +Stylesheets can conflict with each other, and when they do, the browser goes with the one that comes later in the document. React lets you control the order of stylesheets with the `precedence` prop. In this example, three components render stylesheets, and the ones with the same precedence are grouped together in the `<head>`. <SandpackWithHTMLOutput> diff --git a/src/content/reference/react-dom/components/meta.md b/src/content/reference/react-dom/components/meta.md index 20412a32a1c..35a95c5aaf5 100644 --- a/src/content/reference/react-dom/components/meta.md +++ b/src/content/reference/react-dom/components/meta.md @@ -34,7 +34,7 @@ To add document metadata, render the [built-in browser `<meta>` component](https It should have *exactly one* of the following props: `name`, `httpEquiv`, `charset`, `itemProp`. The `<meta>` component does something different depending on which of these props is specified. -* `name`: a string. Specifies the [kind of metadata](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name) to be attached to the document. +* `name`: a string. Specifies the [kind of metadata](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name) to be attached to the document. * `charset`: a string. Specifies the character set used by the document. The only valid value is `"utf-8"`. * `httpEquiv`: a string. Specifies a directive for processing the document. * `itemProp`: a string. Specifies metadata about a particular item within the document rather than the document as a whole. @@ -42,9 +42,9 @@ It should have *exactly one* of the following props: `name`, `httpEquiv`, `chars #### Special rendering behavior {/*special-rendering-behavior*/} -React will always place the DOM element corresponding to the `<meta>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<meta>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render `<meta>` components itself. +React will always place the DOM element corresponding to the `<meta>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<meta>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render `<meta>` components itself. -There is one exception to this: if `<meta>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t represent metadata about the document but rather metadata about a specific part of the page. +There is one exception to this: if `<meta>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t represent metadata about the document but rather metadata about a specific part of the page. --- @@ -52,7 +52,7 @@ There is one exception to this: if `<meta>` has an [`itemProp`](https://develope ### Annotating the document with metadata {/*annotating-the-document-with-metadata*/} -You can annotate the document with metadata such as keywords, a summary, or the author’s name. React will place this metadata within the document `<head>` regardless of where in the React tree it is rendered. +You can annotate the document with metadata such as keywords, a summary, or the author’s name. React will place this metadata within the document `<head>` regardless of where in the React tree it is rendered. ```html <meta name="author" content="John Smith" /> @@ -83,7 +83,7 @@ export default function SiteMapPage() { ### Annotating specific items within the document with metadata {/*annotating-specific-items-within-the-document-with-metadata*/} -You can use the `<meta>` component with the `itemProp` prop to annotate specific items within the document with metadata. In this case, React will *not* place these annotations within the document `<head>` but will place them like any other React component. +You can use the `<meta>` component with the `itemProp` prop to annotate specific items within the document with metadata. In this case, React will *not* place these annotations within the document `<head>` but will place them like any other React component. ```js <section itemScope> diff --git a/src/content/reference/react-dom/components/option.md b/src/content/reference/react-dom/components/option.md index 82a621fd6dc..f523e0da843 100644 --- a/src/content/reference/react-dom/components/option.md +++ b/src/content/reference/react-dom/components/option.md @@ -79,5 +79,5 @@ export default function FruitPicker() { select { margin: 5px; } ``` -</Sandpack> +</Sandpack> diff --git a/src/content/reference/react-dom/components/script.md b/src/content/reference/react-dom/components/script.md index 6febd8465d2..06032a8935b 100644 --- a/src/content/reference/react-dom/components/script.md +++ b/src/content/reference/react-dom/components/script.md @@ -46,7 +46,7 @@ Other supported props: * `integrity`: a string. A cryptographic hash of the script, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). * `noModule`: a boolean. Disables the script in browsers that support ES modules — allowing for a fallback script for browsers that do not. * `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. -* `referrer`: a string. Says [what Referer header to send](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#referrerpolicy) when fetching the script and any resources that the script fetches in turn. +* `referrer`: a string. Says [what Referer header to send](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#referrerpolicy) when fetching the script and any resources that the script fetches in turn. * `type`: a string. Says whether the script is a [classic script, ES module, or import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type). Props that disable React's [special treatment of scripts](#special-rendering-behavior): diff --git a/src/content/reference/react-dom/components/select.md b/src/content/reference/react-dom/components/select.md index f30dc53f434..72033ea0ac0 100644 --- a/src/content/reference/react-dom/components/select.md +++ b/src/content/reference/react-dom/components/select.md @@ -103,7 +103,7 @@ export default function FruitPicker() { select { margin: 5px; } ``` -</Sandpack> +</Sandpack> --- @@ -178,7 +178,7 @@ export default function FruitPicker() { select { margin: 5px; } ``` -</Sandpack> +</Sandpack> <Pitfall> diff --git a/src/content/reference/react-dom/components/title.md b/src/content/reference/react-dom/components/title.md index 9c6d85af82c..9e4d8e65ae4 100644 --- a/src/content/reference/react-dom/components/title.md +++ b/src/content/reference/react-dom/components/title.md @@ -36,11 +36,11 @@ To specify the title of the document, render the [built-in browser `<title>` com #### Special rendering behavior {/*special-rendering-behavior*/} -React will always place the DOM element corresponding to the `<title>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<title>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render its `<title>` itself. +React will always place the DOM element corresponding to the `<title>` component within the document’s `<head>`, regardless of where in the React tree it is rendered. The `<head>` is the only valid place for `<title>` to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render its `<title>` itself. There are two exception to this: * If `<title>` is within an `<svg>` component, then there is no special behavior, because in this context it doesn’t represent the document’s title but rather is an [accessibility annotation for that SVG graphic](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title). -* If the `<title>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t represent the document’s title but rather metadata about a specific part of the page. +* If the `<title>` has an [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop) prop, there is no special behavior, because in this case it doesn’t represent the document’s title but rather metadata about a specific part of the page. <Pitfall> diff --git a/src/content/reference/react-dom/hooks/useFormStatus.md b/src/content/reference/react-dom/hooks/useFormStatus.md index 0fc83e3e18d..7517d8ae22f 100644 --- a/src/content/reference/react-dom/hooks/useFormStatus.md +++ b/src/content/reference/react-dom/hooks/useFormStatus.md @@ -40,7 +40,7 @@ export default function App() { } ``` -To get status information, the `Submit` component must be rendered within a `<form>`. The Hook returns information like the <CodeStep step={1}>`pending`</CodeStep> property which tells you if the form is actively submitting. +To get status information, the `Submit` component must be rendered within a `<form>`. The Hook returns information like the <CodeStep step={1}>`pending`</CodeStep> property which tells you if the form is actively submitting. In the above example, `Submit` uses this information to disable `<button>` presses while the form is submitting. @@ -65,7 +65,7 @@ A `status` object with the following properties: #### Caveats {/*caveats*/} -* The `useFormStatus` Hook must be called from a component that is rendered inside a `<form>`. +* The `useFormStatus` Hook must be called from a component that is rendered inside a `<form>`. * `useFormStatus` will only return status information for a parent `<form>`. It will not return status information for any `<form>` rendered in that same component or children components. --- @@ -75,7 +75,7 @@ A `status` object with the following properties: ### Display a pending state during form submission {/*display-a-pending-state-during-form-submission*/} To display a pending state while a form is submitting, you can call the `useFormStatus` Hook in a component rendered in a `<form>` and read the `pending` property returned. -Here, we use the `pending` property to indicate the form is submitting. +Here, we use the `pending` property to indicate the form is submitting. <Sandpack> @@ -110,7 +110,7 @@ export async function submitForm(query) { await new Promise((res) => setTimeout(res, 1000)); } ``` -</Sandpack> +</Sandpack> <Pitfall> @@ -132,7 +132,7 @@ Instead call `useFormStatus` from inside a component that is located inside `<fo ```js function Submit() { // ✅ `pending` will be derived from the form that wraps the Submit component - const { pending } = useFormStatus(); + const { pending } = useFormStatus(); return <button disabled={pending}>...</button>; } @@ -215,7 +215,7 @@ button { ``` -</Sandpack> +</Sandpack> --- @@ -223,7 +223,7 @@ button { ### `status.pending` is never `true` {/*pending-is-never-true*/} -`useFormStatus` will only return status information for a parent `<form>`. +`useFormStatus` will only return status information for a parent `<form>`. If the component that calls `useFormStatus` is not nested in a `<form>`, `status.pending` will always return `false`. Verify `useFormStatus` is called in a component that is a child of a `<form>` element. diff --git a/src/content/reference/react-dom/preconnect.md b/src/content/reference/react-dom/preconnect.md index 047b1fcac73..f28de8776fc 100644 --- a/src/content/reference/react-dom/preconnect.md +++ b/src/content/reference/react-dom/preconnect.md @@ -34,7 +34,7 @@ function AppRoot() { [See more examples below.](#usage) -The `preconnect` function provides the browser with a hint that it should open a connection to the given server. If the browser chooses to do so, this can speed up the loading of resources from that server. +The `preconnect` function provides the browser with a hint that it should open a connection to the given server. If the browser chooses to do so, this can speed up the loading of resources from that server. #### Parameters {/*parameters*/} diff --git a/src/content/reference/react-dom/prefetchDNS.md b/src/content/reference/react-dom/prefetchDNS.md index ef11aa3e53f..c9229bba266 100644 --- a/src/content/reference/react-dom/prefetchDNS.md +++ b/src/content/reference/react-dom/prefetchDNS.md @@ -34,7 +34,7 @@ function AppRoot() { [See more examples below.](#usage) -The prefetchDNS function provides the browser with a hint that it should look up the IP address of a given server. If the browser chooses to do so, this can speed up the loading of resources from that server. +The prefetchDNS function provides the browser with a hint that it should look up the IP address of a given server. If the browser chooses to do so, this can speed up the loading of resources from that server. #### Parameters {/*parameters*/} diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md index 5dcaaf9338e..d9f3808c465 100644 --- a/src/content/reference/react-dom/preinit.md +++ b/src/content/reference/react-dom/preinit.md @@ -47,10 +47,10 @@ The `preinit` function provides the browser with a hint that it should start dow * `href`: a string. The URL of the resource you want to download and execute. * `options`: an object. It contains the following properties: * `as`: a required string. The type of resource. Its possible values are `script` and `style`. - * `precedence`: a string. Required with stylesheets. Says where to insert the stylesheet relative to others. Stylesheets with higher precedence can override those with lower precedence. The possible values are `reset`, `low`, `medium`, `high`. + * `precedence`: a string. Required with stylesheets. Says where to insert the stylesheet relative to others. Stylesheets with higher precedence can override those with lower precedence. The possible values are `reset`, `low`, `medium`, `high`. * `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. * `integrity`: a string. A cryptographic hash of the resource, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). - * `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. + * `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. * `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`. #### Returns {/*returns*/} diff --git a/src/content/reference/react-dom/preinitModule.md b/src/content/reference/react-dom/preinitModule.md index 93a4a730f9c..72c443291e7 100644 --- a/src/content/reference/react-dom/preinitModule.md +++ b/src/content/reference/react-dom/preinitModule.md @@ -49,7 +49,7 @@ The `preinitModule` function provides the browser with a hint that it should sta * `as`: a required string. It must be `'script'`. * `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. * `integrity`: a string. A cryptographic hash of the module, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). - * `nonce`: a string. A cryptographic [nonce to allow the module](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. + * `nonce`: a string. A cryptographic [nonce to allow the module](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. #### Returns {/*returns*/} diff --git a/src/content/reference/react-dom/preload.md b/src/content/reference/react-dom/preload.md index e9d00fc608b..5d625d23672 100644 --- a/src/content/reference/react-dom/preload.md +++ b/src/content/reference/react-dom/preload.md @@ -51,7 +51,7 @@ The `preload` function provides the browser with a hint that it should start dow * `referrerPolicy`: a string. The [Referrer header](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#referrerpolicy) to send when fetching. Its possible values are `no-referrer-when-downgrade` (the default), `no-referrer`, `origin`, `origin-when-cross-origin`, and `unsafe-url`. * `integrity`: a string. A cryptographic hash of the resource, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). * `type`: a string. The MIME type of the resource. - * `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. + * `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. * `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`. * `imageSrcSet`: a string. For use only with `as: "image"`. Specifies the [source set of the image](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images). * `imageSizes`: a string. For use only with `as: "image"`. Specifies the [sizes of the image](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images). diff --git a/src/content/reference/react-dom/preloadModule.md b/src/content/reference/react-dom/preloadModule.md index 944d438fc83..c26b4878f6a 100644 --- a/src/content/reference/react-dom/preloadModule.md +++ b/src/content/reference/react-dom/preloadModule.md @@ -49,7 +49,7 @@ The `preloadModule` function provides the browser with a hint that it should sta * `as`: a required string. It must be `'script'`. * `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`. * `integrity`: a string. A cryptographic hash of the module, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). - * `nonce`: a string. A cryptographic [nonce to allow the module](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. + * `nonce`: a string. A cryptographic [nonce to allow the module](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy. #### Returns {/*returns*/} diff --git a/src/content/reference/react-dom/server/renderToPipeableStream.md b/src/content/reference/react-dom/server/renderToPipeableStream.md index 7d0d1ab3dbb..84b8873a6fd 100644 --- a/src/content/reference/react-dom/server/renderToPipeableStream.md +++ b/src/content/reference/react-dom/server/renderToPipeableStream.md @@ -294,7 +294,7 @@ Suspense **does not** detect when data is fetched inside an Effect or event hand The exact way you would load data in the `Posts` component above depends on your framework. If you use a Suspense-enabled framework, you'll find the details in its data fetching documentation. -Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. +Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. </Note> @@ -401,7 +401,7 @@ const { pipe } = renderToPipeableStream(<App />, { onShellError(error) { response.statusCode = 500; response.setHeader('content-type', 'text/html'); - response.send('<h1>Something went wrong</h1>'); + response.send('<h1>Something went wrong</h1>'); }, onError(error) { console.error(error); @@ -460,7 +460,7 @@ const { pipe } = renderToPipeableStream(<App />, { onShellError(error) { response.statusCode = 500; response.setHeader('content-type', 'text/html'); - response.send('<h1>Something went wrong</h1>'); + response.send('<h1>Something went wrong</h1>'); }, onError(error) { console.error(error); @@ -486,7 +486,7 @@ const { pipe } = renderToPipeableStream(<App />, { onShellError(error) { response.statusCode = 500; response.setHeader('content-type', 'text/html'); - response.send('<h1>Something went wrong</h1>'); + response.send('<h1>Something went wrong</h1>'); }, onError(error) { didError = true; @@ -530,7 +530,7 @@ const { pipe } = renderToPipeableStream(<App />, { onShellError(error) { response.statusCode = getStatusCode(); response.setHeader('content-type', 'text/html'); - response.send('<h1>Something went wrong</h1>'); + response.send('<h1>Something went wrong</h1>'); }, onError(error) { didError = true; @@ -570,13 +570,13 @@ const { pipe } = renderToPipeableStream(<App />, { onShellError(error) { response.statusCode = 500; response.setHeader('content-type', 'text/html'); - response.send('<h1>Something went wrong</h1>'); + response.send('<h1>Something went wrong</h1>'); }, onAllReady() { if (isCrawler) { response.statusCode = didError ? 500 : 200; response.setHeader('content-type', 'text/html'); - pipe(response); + pipe(response); } }, onError(error) { diff --git a/src/content/reference/react-dom/server/renderToReadableStream.md b/src/content/reference/react-dom/server/renderToReadableStream.md index f407f2245f4..f3e862124af 100644 --- a/src/content/reference/react-dom/server/renderToReadableStream.md +++ b/src/content/reference/react-dom/server/renderToReadableStream.md @@ -293,7 +293,7 @@ Suspense **does not** detect when data is fetched inside an Effect or event hand The exact way you would load data in the `Posts` component above depends on your framework. If you use a Suspense-enabled framework, you'll find the details in its data fetching documentation. -Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. +Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. </Note> diff --git a/src/content/reference/react-dom/server/resume.md b/src/content/reference/react-dom/server/resume.md index 17b48b2acf6..ad61f6da561 100644 --- a/src/content/reference/react-dom/server/resume.md +++ b/src/content/reference/react-dom/server/resume.md @@ -75,7 +75,7 @@ The returned stream has an additional property: <Sandpack> -```js src/App.js hidden +```js src/App.js hidden ``` ```html public/index.html diff --git a/src/content/reference/react/Activity.md b/src/content/reference/react/Activity.md index b79bed9e2a7..127a4b8d0ae 100644 --- a/src/content/reference/react/Activity.md +++ b/src/content/reference/react/Activity.md @@ -43,7 +43,7 @@ In this way, Activity can be thought of as a mechanism for rendering "background #### Props {/*props*/} * `children`: The UI you intend to show and hide. -* `mode`: A string value of either `'visible'` or `'hidden'`. If omitted, defaults to `'visible'`. +* `mode`: A string value of either `'visible'` or `'hidden'`. If omitted, defaults to `'visible'`. #### Caveats {/*caveats*/} @@ -111,7 +111,7 @@ import { useState } from 'react'; export default function Sidebar() { const [isExpanded, setIsExpanded] = useState(false) - + return ( <nav> <button onClick={() => setIsExpanded(!isExpanded)}> @@ -219,7 +219,7 @@ import { useState } from 'react'; export default function Sidebar() { const [isExpanded, setIsExpanded] = useState(false) - + return ( <nav> <button onClick={() => setIsExpanded(!isExpanded)}> @@ -287,7 +287,7 @@ In this example, the Contact tab has a `<textarea>` where the user can enter a m <Sandpack> -```js src/App.js +```js src/App.js import { useState } from 'react'; import TabButton from './TabButton.js'; import Home from './Home.js'; @@ -434,7 +434,7 @@ export default function Home() { } ``` -```js src/Contact.js +```js src/Contact.js export default function Contact() { return ( <div> @@ -765,7 +765,7 @@ Activity **does not** detect data that is fetched inside an Effect. The exact way you would load data in the `Posts` component above depends on your framework. If you use a Suspense-enabled framework, you'll find the details in its data fetching documentation. -Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. +Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. </Note> @@ -903,7 +903,7 @@ function Page() { </Activity> </> ); -} +} ``` --- @@ -975,7 +975,7 @@ export default function Home() { } ``` -```js src/Video.js +```js src/Video.js export default function Video() { return ( <video @@ -1068,7 +1068,7 @@ export default function Home() { } ``` -```js src/Video.js +```js src/Video.js export default function Video() { return ( <video @@ -1185,7 +1185,7 @@ export default function Home() { } ``` -```js src/Video.js +```js src/Video.js import { useRef, useLayoutEffect } from 'react'; export default function Video() { @@ -1238,7 +1238,7 @@ The most common cases of this will be from the following tags: Typically, though, most of your React components should already be robust to being hidden by an Activity boundary. And conceptually, you should think of "hidden" Activities as being unmounted. -To eagerly discover other Effects that don't have proper cleanup, which is important not only for Activity boundaries but for many other behaviors in React, we recommend using [`<StrictMode>`](/reference/react/StrictMode). +To eagerly discover other Effects that don't have proper cleanup, which is important not only for Activity boundaries but for many other behaviors in React, we recommend using [`<StrictMode>`](/reference/react/StrictMode). --- @@ -1249,4 +1249,4 @@ When an `<Activity>` is "hidden", all its children's Effects are cleaned up. Con If you're relying on an Effect mounting to clean up a component's side effects, refactor the Effect to do the work in the returned cleanup function instead. -To eagerly find problematic Effects, we recommend adding [`<StrictMode>`](/reference/react/StrictMode) which will eagerly perform Activity unmounts and mounts to catch any unexpected side-effects. +To eagerly find problematic Effects, we recommend adding [`<StrictMode>`](/reference/react/StrictMode) which will eagerly perform Activity unmounts and mounts to catch any unexpected side-effects. diff --git a/src/content/reference/react/Children.md b/src/content/reference/react/Children.md index 81a28c5b38d..3647b1eed1d 100644 --- a/src/content/reference/react/Children.md +++ b/src/content/reference/react/Children.md @@ -492,7 +492,7 @@ As mentioned earlier, there is no way to get the rendered output of an inner com ### Converting children to an array {/*converting-children-to-an-array*/} -Call `Children.toArray(children)` to turn the `children` data structure into a regular JavaScript array. This lets you manipulate the array with built-in array methods like [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), or [`reverse`.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) +Call `Children.toArray(children)` to turn the `children` data structure into a regular JavaScript array. This lets you manipulate the array with built-in array methods like [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), or [`reverse`.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) <Sandpack> @@ -861,7 +861,7 @@ export default function App() { return ( <Row isHighlighted={index % 2 === 0}> <p>This is the {id} item.</p> - </Row> + </Row> ); }} /> diff --git a/src/content/reference/react/Component.md b/src/content/reference/react/Component.md index 2509aa7598a..3b882f09762 100644 --- a/src/content/reference/react/Component.md +++ b/src/content/reference/react/Component.md @@ -117,7 +117,7 @@ class Counter extends Component { handleAgeChange = () => { this.setState({ - age: this.state.age + 1 + age: this.state.age + 1 }); }; @@ -724,7 +724,7 @@ Return `false` to tell React that re-rendering can be skipped. #### Caveats {/*shouldcomponentupdate-caveats*/} -- This method *only* exists as a performance optimization. If your component breaks without it, fix that first. +- This method *only* exists as a performance optimization. If your component breaks without it, fix that first. - Consider using [`PureComponent`](/reference/react/PureComponent) instead of writing `shouldComponentUpdate` by hand. `PureComponent` shallowly compares props and state, and reduces the chance that you'll skip a necessary update. @@ -1098,7 +1098,7 @@ export default class Counter extends Component { handleAgeChange = () => { this.setState({ - age: this.state.age + 1 + age: this.state.age + 1 }); }; @@ -1123,7 +1123,7 @@ export default class Counter extends Component { button { display: block; margin-top: 10px; } ``` -</Sandpack> +</Sandpack> <Pitfall> @@ -1207,7 +1207,7 @@ export default class ChatRoom extends Component { this.state.serverUrl, this.props.roomId ); - this.connection.connect(); + this.connection.connect(); } destroyConnection() { @@ -1275,7 +1275,7 @@ By default, if your application throws an error during rendering, React will rem Error boundaries do not catch errors for: - Event handlers [(learn more)](/learn/responding-to-events) -- [Server side rendering](/reference/react-dom/server) +- [Server side rendering](/reference/react-dom/server) - Errors thrown in the error boundary itself (rather than its children) - Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks); an exception is the usage of the [`startTransition`](/reference/react/useTransition#starttransition) function returned by the [`useTransition`](/reference/react/useTransition) Hook. Errors thrown inside the transition function are caught by error boundaries [(learn more)](/reference/react/useTransition#displaying-an-error-to-users-with-error-boundary) @@ -1439,7 +1439,7 @@ export default class Counter extends Component { handleAgeChange = (e) => { this.setState({ - age: this.state.age + 1 + age: this.state.age + 1 }); }; @@ -1606,7 +1606,7 @@ export default class ChatRoom extends Component { this.state.serverUrl, this.props.roomId ); - this.connection.connect(); + this.connection.connect(); } destroyConnection() { @@ -1795,7 +1795,7 @@ class Panel extends Component { <h1>{this.props.title}</h1> {this.props.children} </section> - ); + ); } } diff --git a/src/content/reference/react/Fragment.md b/src/content/reference/react/Fragment.md index 7399ee2401f..5ffc4527739 100644 --- a/src/content/reference/react/Fragment.md +++ b/src/content/reference/react/Fragment.md @@ -4,7 +4,7 @@ title: <Fragment> (<>...</>) <Intro> -`<Fragment>`, often used via `<>...</>` syntax, lets you group elements without a wrapper node. +`<Fragment>`, often used via `<>...</>` syntax, lets you group elements without a wrapper node. <Canary> Fragments can also accept refs, which enable interacting with underlying DOM nodes without adding wrapper elements. See reference and usage below.</Canary> @@ -43,7 +43,7 @@ When you pass a ref to a fragment, React provides a `FragmentInstance` object wi **Layout methods:** - `compareDocumentPosition(otherNode)`: Compares the document position of the Fragment with another node. - - If the Fragment has children, the native `compareDocumentPosition` value is returned. + - If the Fragment has children, the native `compareDocumentPosition` value is returned. - Empty Fragments will attempt to compare positioning within the React tree and include `Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC`. - Elements that have a different relationship in the React tree and DOM tree due to portaling or other insertions are `Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC`. - `getClientRects()`: Returns a flat array of `DOMRect` objects representing the bounding rectangles of all children. @@ -279,7 +279,7 @@ function VisibilityObserverFragment({ threshold = 0.5, onVisibilityChange, child }, { threshold } ); - + fragmentRef.current.observeUsing(observer); return () => fragmentRef.current.unobserveUsing(observer); }, [threshold, onVisibilityChange]); diff --git a/src/content/reference/react/Suspense.md b/src/content/reference/react/Suspense.md index fa5b4439ffe..c2fc0b6ef55 100644 --- a/src/content/reference/react/Suspense.md +++ b/src/content/reference/react/Suspense.md @@ -215,7 +215,7 @@ Suspense **does not** detect when data is fetched inside an Effect or event hand The exact way you would load data in the `Albums` component above depends on your framework. If you use a Suspense-enabled framework, you'll find the details in its data fetching documentation. -Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. +Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. </Note> @@ -362,9 +362,9 @@ async function getBio() { setTimeout(resolve, 1500); }); - return `The Beatles were an English rock band, - formed in Liverpool in 1960, that comprised - John Lennon, Paul McCartney, George Harrison + return `The Beatles were an English rock band, + formed in Liverpool in 1960, that comprised + John Lennon, Paul McCartney, George Harrison and Ringo Starr.`; } @@ -624,9 +624,9 @@ async function getBio() { setTimeout(resolve, 500); }); - return `The Beatles were an English rock band, - formed in Liverpool in 1960, that comprised - John Lennon, Paul McCartney, George Harrison + return `The Beatles were an English rock band, + formed in Liverpool in 1960, that comprised + John Lennon, Paul McCartney, George Harrison and Ringo Starr.`; } @@ -877,7 +877,7 @@ input { margin: 10px; } </Sandpack> -A common alternative UI pattern is to *defer* updating the list and to keep showing the previous results until the new results are ready. The [`useDeferredValue`](/reference/react/useDeferredValue) Hook lets you pass a deferred version of the query down: +A common alternative UI pattern is to *defer* updating the list and to keep showing the previous results until the new results are ready. The [`useDeferredValue`](/reference/react/useDeferredValue) Hook lets you pass a deferred version of the query down: ```js {3,11} export default function App() { @@ -903,7 +903,7 @@ To make it more obvious to the user, you can add a visual indication when the st ```js {2} <div style={{ - opacity: query !== deferredQuery ? 0.5 : 1 + opacity: query !== deferredQuery ? 0.5 : 1 }}> <SearchResults query={deferredQuery} /> </div> @@ -1251,9 +1251,9 @@ async function getBio() { setTimeout(resolve, 500); }); - return `The Beatles were an English rock band, - formed in Liverpool in 1960, that comprised - John Lennon, Paul McCartney, George Harrison + return `The Beatles were an English rock band, + formed in Liverpool in 1960, that comprised + John Lennon, Paul McCartney, George Harrison and Ringo Starr.`; } @@ -1375,7 +1375,7 @@ function Router() { function navigate(url) { startTransition(() => { - setPage(url); + setPage(url); }); } // ... @@ -1563,9 +1563,9 @@ async function getBio() { setTimeout(resolve, 500); }); - return `The Beatles were an English rock band, - formed in Liverpool in 1960, that comprised - John Lennon, Paul McCartney, George Harrison + return `The Beatles were an English rock band, + formed in Liverpool in 1960, that comprised + John Lennon, Paul McCartney, George Harrison and Ringo Starr.`; } @@ -1874,9 +1874,9 @@ async function getBio() { setTimeout(resolve, 500); }); - return `The Beatles were an English rock band, - formed in Liverpool in 1960, that comprised - John Lennon, Paul McCartney, George Harrison + return `The Beatles were an English rock band, + formed in Liverpool in 1960, that comprised + John Lennon, Paul McCartney, George Harrison and Ringo Starr.`; } diff --git a/src/content/reference/react/ViewTransition.md b/src/content/reference/react/ViewTransition.md index d3f4a3b6533..1ad03af69e1 100644 --- a/src/content/reference/react/ViewTransition.md +++ b/src/content/reference/react/ViewTransition.md @@ -81,7 +81,7 @@ After the finished Promise of the `startViewTransition` is resolved, React will #### Caveats {/*caveats*/} -- Only use `name` for [shared element transitions](#animating-a-shared-element). For all other animations, React automatically generates a unique name to prevent unexpected animations. +- Only use `name` for [shared element transitions](#animating-a-shared-element). For all other animations, React automatically generates a unique name to prevent unexpected animations. - By default, `setState` updates immediately and does not activate `<ViewTransition>`, only updates wrapped in a [Transition](/reference/react/useTransition), [`<Suspense>`](/reference/react/Suspense), or `useDeferredValue` activate ViewTransition. - `<ViewTransition>` creates an image that can be moved around, scaled and cross-faded. Unlike Layout Animations you may have seen in React Native or Motion, this means that not every individual Element inside of it animates its position. This can lead to better performance and a more continuous feeling, smooth animation compared to animating every individual piece. However, it can also lose continuity in things that should be moving by themselves. So you might have to add more `<ViewTransition>` boundaries manually as a result. - Currently, `<ViewTransition>` only works in the DOM. We're working on adding support for React Native and other platforms. @@ -156,7 +156,7 @@ For example, you can define a ViewTransition as: /* apply slide-in for Transition Type `forward` */ "forward": 'slide-in', /* otherwise use the browser default animation */ - "default": 'auto' + "default": 'auto' }} /* use the browser default for exit animations*/ exit="auto" @@ -449,7 +449,7 @@ button:hover { #### Only top-level ViewTransitions animate on exit/enter {/*only-top-level-viewtransition-animates-on-exit-enter*/} -`<ViewTransition>` only activates exit/enter if it is placed _before_ any DOM nodes. +`<ViewTransition>` only activates exit/enter if it is placed _before_ any DOM nodes. If there's a `<div>` above `<ViewTransition>`, no exit/enter animations trigger: @@ -2336,7 +2336,7 @@ Each callback receives an `instance` with `.old` and `.new` properties represent </ViewTransition> ``` -This allows you to combine CSS-driven animations and JavaScript-driven animations. +This allows you to combine CSS-driven animations and JavaScript-driven animations. In the following example, the default cross-fade is handled by CSS, and the slide animations are driven by JavaScript in the `onEnter` and `onExit` animations: @@ -2564,7 +2564,7 @@ This allows the browser to cancel the animation when the View Transition is inte ### Animating transition types with JavaScript {/*animating-transition-types-with-javascript*/} -You can use `types` passed to `ViewTransition` events to conditionally apply different animations based on how the Transition was triggered. +You can use `types` passed to `ViewTransition` events to conditionally apply different animations based on how the Transition was triggered. ```js {3} <ViewTransition diff --git a/src/content/reference/react/act.md b/src/content/reference/react/act.md index 7e1273e3d74..007e2cb0fe1 100644 --- a/src/content/reference/react/act.md +++ b/src/content/reference/react/act.md @@ -96,12 +96,12 @@ import Counter from './Counter'; it('can render and update a counter', async () => { container = document.createElement('div'); document.body.appendChild(container); - + // ✅ Render the component inside act(). await act(() => { ReactDOMClient.createRoot(container).render(<Counter />); }); - + const button = container.querySelector('button'); const label = container.querySelector('p'); expect(label.textContent).toBe('You clicked 0 times'); @@ -125,11 +125,11 @@ import Counter from './Counter'; it.only('can render and update a counter', async () => { const container = document.createElement('div'); document.body.appendChild(container); - + await act( async () => { ReactDOMClient.createRoot(container).render(<Counter />); }); - + // ✅ Dispatch the event inside act(). await act(async () => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })); diff --git a/src/content/reference/react/addTransitionType.md b/src/content/reference/react/addTransitionType.md index 2557f05649e..f6c6f39b265 100644 --- a/src/content/reference/react/addTransitionType.md +++ b/src/content/reference/react/addTransitionType.md @@ -5,7 +5,7 @@ version: canary <Canary> -**The `addTransitionType` API is currently only available in React’s Canary and Experimental channels.** +**The `addTransitionType` API is currently only available in React’s Canary and Experimental channels.** [Learn more about React’s release channels here.](/community/versioning-policy#all-release-channels) @@ -76,7 +76,7 @@ Currently, Transition Types can be used to customize different animations based - [Customize animations using browser view transition types](#customize-animations-using-browser-view-transition-types) - [Customize animations using `View Transition` Class](#customize-animations-using-view-transition-class) -- [Customize animations using `ViewTransition` events](#customize-animations-using-viewtransition-events) +- [Customize animations using `ViewTransition` events](#customize-animations-using-viewtransition-events) In the future, we plan to support more use cases for using the cause of a transition. diff --git a/src/content/reference/react/captureOwnerStack.md b/src/content/reference/react/captureOwnerStack.md index 7e4fe79fe17..b7516791ed9 100644 --- a/src/content/reference/react/captureOwnerStack.md +++ b/src/content/reference/react/captureOwnerStack.md @@ -257,7 +257,7 @@ pre.nowrap { } .hidden { - display: none; + display: none; } ``` diff --git a/src/content/reference/react/cloneElement.md b/src/content/reference/react/cloneElement.md index 4e29ff203b1..91d501b7203 100644 --- a/src/content/reference/react/cloneElement.md +++ b/src/content/reference/react/cloneElement.md @@ -103,7 +103,7 @@ export default function List({ children }) { <div className="List"> {Children.map(children, (child, index) => cloneElement(child, { - isHighlighted: index === selectedIndex + isHighlighted: index === selectedIndex }) )} ``` @@ -124,15 +124,15 @@ By cloning its children, the `List` can pass extra information to every `Row` in <List> <Row title="Cabbage" - isHighlighted={true} + isHighlighted={true} /> <Row title="Garlic" - isHighlighted={false} + isHighlighted={false} /> <Row title="Apple" - isHighlighted={false} + isHighlighted={false} /> </List> ``` @@ -152,7 +152,7 @@ export default function App() { {products.map(product => <Row key={product.id} - title={product.title} + title={product.title} /> )} </List> @@ -169,7 +169,7 @@ export default function List({ children }) { <div className="List"> {Children.map(children, (child, index) => cloneElement(child, { - isHighlighted: index === selectedIndex + isHighlighted: index === selectedIndex }) )} <hr /> @@ -246,7 +246,7 @@ Cloning children makes it hard to tell how the data flows through your app. Try ### Passing data with a render prop {/*passing-data-with-a-render-prop*/} -Instead of using `cloneElement`, consider accepting a *render prop* like `renderItem`. Here, `List` receives `renderItem` as a prop. `List` calls `renderItem` for every item and passes `isHighlighted` as an argument: +Instead of using `cloneElement`, consider accepting a *render prop* like `renderItem`. Here, `List` receives `renderItem` as a prop. `List` calls `renderItem` for every item and passes `isHighlighted` as an argument: ```js {1,7} export default function List({ items, renderItem }) { @@ -280,15 +280,15 @@ The end result is the same as with `cloneElement`: <List> <Row title="Cabbage" - isHighlighted={true} + isHighlighted={true} /> <Row title="Garlic" - isHighlighted={false} + isHighlighted={false} /> <Row title="Apple" - isHighlighted={false} + isHighlighted={false} /> </List> ``` diff --git a/src/content/reference/react/createContext.md b/src/content/reference/react/createContext.md index 2161fa63c69..e4e9bcf6219 100644 --- a/src/content/reference/react/createContext.md +++ b/src/content/reference/react/createContext.md @@ -64,7 +64,7 @@ function App() { <Note> -Starting in React 19, you can render `<SomeContext>` as a provider. +Starting in React 19, you can render `<SomeContext>` as a provider. In older versions of React, use `<SomeContext.Provider>`. diff --git a/src/content/reference/react/experimental_taintUniqueValue.md b/src/content/reference/react/experimental_taintUniqueValue.md index ea92ff6bef6..bea4b627da8 100644 --- a/src/content/reference/react/experimental_taintUniqueValue.md +++ b/src/content/reference/react/experimental_taintUniqueValue.md @@ -77,7 +77,7 @@ experimental_taintUniqueValue( ### Prevent a token from being passed to Client Components {/*prevent-a-token-from-being-passed-to-client-components*/} -To ensure that sensitive information such as passwords, session tokens, or other unique values do not inadvertently get passed to Client Components, the `taintUniqueValue` function provides a layer of protection. When a value is tainted, any attempt to pass it to a Client Component will result in an error. +To ensure that sensitive information such as passwords, session tokens, or other unique values do not inadvertently get passed to Client Components, the `taintUniqueValue` function provides a layer of protection. When a value is tainted, any attempt to pass it to a Client Component will result in an error. The `lifetime` argument defines the duration for which the value remains tainted. For values that should remain tainted indefinitely, objects like [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) or `process` can serve as the `lifetime` argument. These objects have a lifespan that spans the entire duration of your app's execution. @@ -178,7 +178,7 @@ export function fetchAPI(url) { } ``` -Sometimes mistakes happen during refactoring and not all of your colleagues might know about this. +Sometimes mistakes happen during refactoring and not all of your colleagues might know about this. To protect against this mistakes happening down the line we can "taint" the actual password: ```js diff --git a/src/content/reference/react/forwardRef.md b/src/content/reference/react/forwardRef.md index f9c4a7a9734..db42bfae066 100644 --- a/src/content/reference/react/forwardRef.md +++ b/src/content/reference/react/forwardRef.md @@ -336,7 +336,7 @@ const FormField = forwardRef(function FormField({ label, isRequired }, ref) { ref={ref} label={label} value={value} - onChange={e => setValue(e.target.value)} + onChange={e => setValue(e.target.value)} /> {(isRequired && value === '') && <i>Required</i> diff --git a/src/content/reference/react/use.md b/src/content/reference/react/use.md index dc43fa2289c..c13ad520326 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -64,7 +64,7 @@ import { use } from 'react'; function Button() { const theme = use(ThemeContext); - // ... + // ... ``` `use` returns the <CodeStep step={2}>context value</CodeStep> for the <CodeStep step={1}>context</CodeStep> you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. @@ -456,7 +456,7 @@ Instead, call `use` outside any component closures, where the function that call ```jsx function MessageComponent({messagePromise}) { - // ✅ `use` is being called from a component. + // ✅ `use` is being called from a component. const message = use(messagePromise); // ... ``` diff --git a/src/content/reference/react/useActionState.md b/src/content/reference/react/useActionState.md index 30b76134e46..581eebc634b 100644 --- a/src/content/reference/react/useActionState.md +++ b/src/content/reference/react/useActionState.md @@ -65,7 +65,7 @@ function MyCart({initialState}) { <Note> -`dispatchAction` must be called from an Action. +`dispatchAction` must be called from an Action. You can wrap it in [`startTransition`](/reference/react/startTransition), or pass it to an [Action prop](/reference/react/useTransition#exposing-action-props-from-components). Calls outside that scope won’t be treated as part of the Transition and [log an error](#async-function-outside-transition) on development mode. @@ -100,7 +100,7 @@ Each time you call `dispatchAction`, React calls the `reducerAction` with the `a #### Caveats {/*reduceraction-caveats*/} -* `reducerAction` can be sync or async. It can perform sync actions like showing a notification, or async actions like posting updates to a server. +* `reducerAction` can be sync or async. It can perform sync actions like showing a notification, or async actions like posting updates to a server. * `reducerAction` is not invoked twice in `<StrictMode>` since `reducerAction` is designed to allow side effects. * The return type of `reducerAction` must match the type of `initialState`. If TypeScript infers a mismatch, you may need to explicitly annotate your state type. * If you set state after `await` in the `reducerAction` you currently need to wrap the state update in an additional `startTransition`. See the [startTransition](/reference/react/useTransition#react-doesnt-treat-my-state-update-after-await-as-a-transition) docs for more info. @@ -267,7 +267,7 @@ Try clicking "Add Ticket" multiple times. Every time you click, a new `addToCart **This is intentional in the design of `useActionState`.** -We have to wait for the previous result of `addToCartAction` in order to pass the `prevCount` to the next call to `addToCartAction`. That means React has to wait for the previous Action to finish before calling the next Action. +We have to wait for the previous result of `addToCartAction` in order to pass the `prevCount` to the next call to `addToCartAction`. That means React has to wait for the previous Action to finish before calling the next Action. You can typically solve this by [using with useOptimistic](/reference/react/useActionState#using-with-useoptimistic) but for more complex cases you may want to consider [cancelling queued actions](#cancelling-queued-actions) or not using `useActionState`. @@ -810,7 +810,7 @@ import Total from './Total'; export default function Checkout() { const abortRef = useRef(null); const [count, dispatchAction, isPending] = useActionState(updateCartAction, 0); - + async function addAction() { if (abortRef.current) { abortRef.current.abort(); @@ -1190,7 +1190,7 @@ When used with a [Server Function](/reference/rsc/server-functions), `useActionS </RSC> -See the [`<form>`](/reference/react-dom/components/form#handle-form-submission-with-a-server-function) docs for more information on using Actions with forms. +See the [`<form>`](/reference/react-dom/components/form#handle-form-submission-with-a-server-function) docs for more information on using Actions with forms. --- @@ -1218,16 +1218,16 @@ function Checkout() { // Return the error from the API as state return {...prevState, error: `Could not add quanitiy ${quantity}: ${result.error}`}; } - + if (!isPending) { // Clear the error state for the first dispatch. - return {count: result.count, error: null}; + return {count: result.count, error: null}; } - + // Return the new count, and any errors that happened. return {count: result.count, error: prevState.error}; - - + + }, { count: 0, diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index f69c49af981..02069c363a2 100644 --- a/src/content/reference/react/useContext.md +++ b/src/content/reference/react/useContext.md @@ -60,7 +60,7 @@ import { useContext } from 'react'; function Button() { const theme = useContext(ThemeContext); - // ... + // ... ``` `useContext` returns the <CodeStep step={2}>context value</CodeStep> for the <CodeStep step={1}>context</CodeStep> you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. @@ -845,7 +845,7 @@ export default function AddTask() { type: 'added', id: nextId++, text: text, - }); + }); }}>Add</button> </> ); @@ -1292,7 +1292,7 @@ export const LevelContext = createContext(0); You can pass any values via context, including objects and functions. -```js [[2, 10, "{ currentUser, login }"]] +```js [[2, 10, "{ currentUser, login }"]] function MyApp() { const [currentUser, setCurrentUser] = useState(null); diff --git a/src/content/reference/react/useEffect.md b/src/content/reference/react/useEffect.md index 85389c62e02..218e65ffb1d 100644 --- a/src/content/reference/react/useEffect.md +++ b/src/content/reference/react/useEffect.md @@ -45,7 +45,7 @@ function ChatRoom({ roomId }) { #### Parameters {/*parameters*/} * `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your [component commits](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom), React will run your setup function. After every commit with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function. - + * **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If you omit this argument, your Effect will re-run after every commit of the component. [See the difference between passing an array of dependencies, an empty array, and no dependencies at all.](#examples-dependencies) #### Returns {/*returns*/} @@ -112,7 +112,7 @@ You need to pass two arguments to `useEffect`: - Then, your <CodeStep step={1}>setup code</CodeStep> runs with the new props and state. 3. Your <CodeStep step={2}>cleanup code</CodeStep> runs one final time after your component is removed from the page *(unmounts).* -**Let's illustrate this sequence for the example above.** +**Let's illustrate this sequence for the example above.** When the `ChatRoom` component above gets added to the page, it will connect to the chat room with the initial `serverUrl` and `roomId`. If either `serverUrl` or `roomId` change as a result of a commit (say, if the user picks a different chat room in a dropdown), your Effect will *disconnect from the previous room, and connect to the next one.* When the `ChatRoom` component is removed from the page, your Effect will disconnect one last time. @@ -1082,7 +1082,7 @@ If either `serverUrl` or `roomId` change, your Effect will reconnect to the chat ```js {8} function ChatRoom({ roomId }) { const [serverUrl, setServerUrl] = useState('https://localhost:1234'); - + useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); @@ -1436,7 +1436,7 @@ function Counter() { } ``` -Since `count` is a reactive value, it must be specified in the list of dependencies. However, that causes the Effect to cleanup and setup again every time the `count` changes. This is not ideal. +Since `count` is a reactive value, it must be specified in the list of dependencies. However, that causes the Effect to cleanup and setup again every time the `count` changes. This is not ideal. To fix this, [pass the `c => c + 1` state updater](/reference/react/useState#updating-state-based-on-the-previous-state) to `setCount`: diff --git a/src/content/reference/react/useEffectEvent.md b/src/content/reference/react/useEffectEvent.md index 0b32a837910..97a659138c5 100644 --- a/src/content/reference/react/useEffectEvent.md +++ b/src/content/reference/react/useEffectEvent.md @@ -32,17 +32,17 @@ function ChatRoom({ roomId, theme }) { } ``` -Effect Events are a part of your Effect logic, but they behave more like an event handler. They always “see” the latest values from render (like props and state) without re-synchronizing your Effect, so they're excluded from Effect dependencies. See [Separating Events from Effects](/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects) to learn more. +Effect Events are a part of your Effect logic, but they behave more like an event handler. They always “see” the latest values from render (like props and state) without re-synchronizing your Effect, so they're excluded from Effect dependencies. See [Separating Events from Effects](/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects) to learn more. [See more examples below.](#usage) #### Parameters {/*parameters*/} -* `callback`: A function containing the logic for your Effect Event. The function can accept any number of arguments and return any value. When you call the returned Effect Event function, the `callback` always accesses the latest committed values from render at the time of the call. +* `callback`: A function containing the logic for your Effect Event. The function can accept any number of arguments and return any value. When you call the returned Effect Event function, the `callback` always accesses the latest committed values from render at the time of the call. #### Returns {/*returns*/} -`useEffectEvent` returns an Effect Event function with the same type signature as your `callback`. +`useEffectEvent` returns an Effect Event function with the same type signature as your `callback`. You can call this function inside `useEffect`, `useLayoutEffect`, `useInsertionEffect`, or from within other Effect Events in the same component. diff --git a/src/content/reference/react/useId.md b/src/content/reference/react/useId.md index 44a11b20d32..40446825aff 100644 --- a/src/content/reference/react/useId.md +++ b/src/content/reference/react/useId.md @@ -193,7 +193,7 @@ Inside React, `useId` is generated from the "parent path" of the calling compone ### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/} -If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them: +If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them: <Sandpack> diff --git a/src/content/reference/react/useImperativeHandle.md b/src/content/reference/react/useImperativeHandle.md index 00b9893bee7..ea3f97f8aac 100644 --- a/src/content/reference/react/useImperativeHandle.md +++ b/src/content/reference/react/useImperativeHandle.md @@ -46,7 +46,7 @@ function MyInput({ ref }) { <Note> -Starting with React 19, [`ref` is available as a prop.](/blog/2024/12/05/react-19#ref-as-a-prop) In React 18 and earlier, it was necessary to get the `ref` from [`forwardRef`.](/reference/react/forwardRef) +Starting with React 19, [`ref` is available as a prop.](/blog/2024/12/05/react-19#ref-as-a-prop) In React 18 and earlier, it was necessary to get the `ref` from [`forwardRef`.](/reference/react/forwardRef) </Note> diff --git a/src/content/reference/react/useInsertionEffect.md b/src/content/reference/react/useInsertionEffect.md index 46a482dab8d..c8094014409 100644 --- a/src/content/reference/react/useInsertionEffect.md +++ b/src/content/reference/react/useInsertionEffect.md @@ -45,7 +45,7 @@ function useCSS(rule) { #### Parameters {/*parameters*/} * `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your component is added to the DOM, but before any layout Effects fire, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. When your component is removed from the DOM, React will run your cleanup function. - + * **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component. #### Returns {/*returns*/} diff --git a/src/content/reference/react/useOptimistic.md b/src/content/reference/react/useOptimistic.md index 702f9936ce9..3c802cad137 100644 --- a/src/content/reference/react/useOptimistic.md +++ b/src/content/reference/react/useOptimistic.md @@ -164,7 +164,7 @@ function MyComponent({age, name, todos}) { 2. The <CodeStep step={3}>set function</CodeStep> that lets you temporarily change the state during an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions). * If a <CodeStep step={4}>reducer</CodeStep> is provided, it will run before returning the optimistic state. -To use the <CodeStep step={2}>optimistic state</CodeStep>, call the `set` function inside an Action. +To use the <CodeStep step={2}>optimistic state</CodeStep>, call the `set` function inside an Action. Actions are functions called inside `startTransition`: @@ -215,7 +215,7 @@ import EditName from './EditName'; export default function App() { const [name, setName] = useState('Alice'); - + return <EditName name={name} action={setName} />; } ``` @@ -230,7 +230,7 @@ export default function EditName({ name, action }) { async function submitAction(formData) { const newName = formData.get('name'); setOptimisticName(newName); - + const updatedName = await updateName(newName); startTransition(() => { action(updatedName); @@ -295,7 +295,7 @@ export default function App() { const [count, setCount] = useState(0); return ( <div> - <Button action={async () => { + <Button action={async () => { await submitForm(); startTransition(() => { setCount(c => c + 1); @@ -363,7 +363,7 @@ The pending state will be shown until everything in the `action` prop is finishe <Note> -You can also use [`useTransition`](/reference/react/useTransition) to get pending state via `isPending`. +You can also use [`useTransition`](/reference/react/useTransition) to get pending state via `isPending`. The difference is that `useTransition` gives you the `startTransition` function, while `useOptimistic` works with any Transition. Use whichever fits your component's needs. @@ -391,10 +391,10 @@ export default function App() { startTransition(async () => { const newValue = !optimisticIsLiked console.log('⏳ setting optimistic state: ' + newValue); - + setOptimisticIsLiked(newValue); const updatedValue = await toggleLike(newValue); - + startTransition(() => { console.log('⏳ setting real state: ' + updatedValue ); setIsLiked(updatedValue); @@ -403,11 +403,11 @@ export default function App() { } if (optimisticIsLiked !== isLiked) { - console.log('✅ rendering optimistic state: ' + optimisticIsLiked); + console.log('✅ rendering optimistic state: ' + optimisticIsLiked); } else { console.log('✅ rendering real value: ' + optimisticIsLiked); } - + return ( <button onClick={handleClick}> @@ -452,7 +452,7 @@ See [Updating state based on the current state](#updating-state-based-on-current ### Updating multiple values together {/*updating-multiple-values-together*/} -When an optimistic update affects multiple related values, use a reducer to update them together. This ensures the UI stays consistent. +When an optimistic update affects multiple related values, use a reducer to update them together. This ensures the UI stays consistent. Here's a follow button that updates both the follow state and follower count: @@ -656,7 +656,7 @@ Each optimistic item includes a `pending: true` flag so you can show loading sta ### Handling multiple `action` types {/*handling-multiple-action-types*/} -When you need to handle multiple types of optimistic updates (like adding and removing items), use a reducer pattern with `action` objects. +When you need to handle multiple types of optimistic updates (like adding and removing items), use a reducer pattern with `action` objects. This shopping cart example shows how to handle add and remove with a single reducer: @@ -930,7 +930,7 @@ export async function deleteItem(id) { </Sandpack> -Try deleting 'Deploy to production'. When the delete fails, the item automatically reappears in the list. +Try deleting 'Deploy to production'. When the delete fails, the item automatically reappears in the list. --- @@ -950,7 +950,7 @@ An optimistic state update occurred outside a Transition or Action. To fix, move </ConsoleBlockMulti> -The optimistic setter function must be called inside `startTransition`: +The optimistic setter function must be called inside `startTransition`: ```js // 🚩 Incorrect: outside a Transition @@ -999,7 +999,7 @@ function MyComponent({ items }) { // This runs during render - not allowed! setPending(true); - + // ... } diff --git a/src/content/reference/react/useReducer.md b/src/content/reference/react/useReducer.md index ed3dc68c265..404ebb08770 100644 --- a/src/content/reference/react/useReducer.md +++ b/src/content/reference/react/useReducer.md @@ -38,7 +38,7 @@ function MyComponent() { #### Parameters {/*parameters*/} -* `reducer`: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types. +* `reducer`: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types. * `initialArg`: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the next `init` argument. * **optional** `init`: The initializer function that should return the initial state. If it's not specified, the initial state is set to `initialArg`. Otherwise, the initial state is set to the result of calling `init(initialArg)`. @@ -199,7 +199,7 @@ Actions can have any shape. By convention, it's common to pass objects with a `t ```js {5,9-12} function Form() { const [state, dispatch] = useReducer(reducer, { name: 'Taylor', age: 42 }); - + function handleButtonClick() { dispatch({ type: 'incremented_age' }); } @@ -291,7 +291,7 @@ export default function Form() { dispatch({ type: 'changed_name', nextName: e.target.value - }); + }); } return ( diff --git a/src/content/reference/react/useState.md b/src/content/reference/react/useState.md index 23db1aae5aa..2a17bf3f4d1 100644 --- a/src/content/reference/react/useState.md +++ b/src/content/reference/react/useState.md @@ -607,8 +607,8 @@ export default function Form() { <br /> (located in {person.artwork.city}) </p> - <img - src={person.artwork.image} + <img + src={person.artwork.image} alt={person.artwork.title} /> </> diff --git a/src/content/reference/react/useSyncExternalStore.md b/src/content/reference/react/useSyncExternalStore.md index ce989a2a447..9bb755a4be9 100644 --- a/src/content/reference/react/useSyncExternalStore.md +++ b/src/content/reference/react/useSyncExternalStore.md @@ -107,7 +107,7 @@ It returns the <CodeStep step={3}>snapshot</CodeStep> of the data in the store. React will use these functions to keep your component subscribed to the store and re-render it on changes. -For example, in the sandbox below, `todosStore` is implemented as an external store that stores data outside of React. The `TodosApp` component connects to that external store with the `useSyncExternalStore` Hook. +For example, in the sandbox below, `todosStore` is implemented as an external store that stores data outside of React. The `TodosApp` component connects to that external store with the `useSyncExternalStore` Hook. <Sandpack> @@ -411,13 +411,13 @@ function ChatIndicator() { function subscribe() { // ... } - + const isOnline = useSyncExternalStore(subscribe, getSnapshot); // ... } ``` - + React will resubscribe to your store if you pass a different `subscribe` function between re-renders. If this causes performance issues and you'd like to avoid resubscribing, move the `subscribe` function outside: ```js {1-4} @@ -440,7 +440,7 @@ function ChatIndicator({ userId }) { const subscribe = useCallback(() => { // ... }, [userId]); - + const isOnline = useSyncExternalStore(subscribe, getSnapshot); // ... diff --git a/src/content/reference/rsc/server-functions.md b/src/content/reference/rsc/server-functions.md index c5c7a97770a..34ef4c00268 100644 --- a/src/content/reference/rsc/server-functions.md +++ b/src/content/reference/rsc/server-functions.md @@ -22,7 +22,7 @@ Server Functions allow Client Components to call async functions executed on the #### How do I build support for Server Functions? {/*how-do-i-build-support-for-server-functions*/} -While Server Functions in React 19 are stable and will not break between minor versions, the underlying APIs used to implement Server Functions in a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x. +While Server Functions in React 19 are stable and will not break between minor versions, the underlying APIs used to implement Server Functions in a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x. To support Server Functions as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement Server Functions in the future. @@ -46,7 +46,7 @@ function EmptyNote () { async function createNoteAction() { // Server Function 'use server'; - + await db.notes.create(); } @@ -59,8 +59,8 @@ When React renders the `EmptyNote` Server Component, it will create a reference ```js {5} "use client"; -export default function Button({onClick}) { - console.log(onClick); +export default function Button({onClick}) { + console.log(onClick); // {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNoteAction'} return <button onClick={() => onClick()}>Create Empty Note</button> } @@ -133,7 +133,7 @@ function UpdateName() { } }) } - + return ( <form action={submitAction}> <input type="text" name="name" disabled={isPending}/> diff --git a/src/utils/forwardRefWithAs.tsx b/src/utils/forwardRefWithAs.tsx index c5975c1993d..3709e3b45f6 100644 --- a/src/utils/forwardRefWithAs.tsx +++ b/src/utils/forwardRefWithAs.tsx @@ -109,7 +109,7 @@ export function forwardRefWithAs<Props, ComponentType extends As>( } /* -Test components to make sure our dynamic As prop components work as intended +Test components to make sure our dynamic As prop components work as intended type PopupProps = { lol: string; children?: React.ReactNode | ((value?: number) => JSX.Element);