diff --git a/.github/ISSUE_TEMPLATE/0-bug.yml b/.github/ISSUE_TEMPLATE/0-bug.yml new file mode 100644 index 00000000..56d2e854 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/0-bug.yml @@ -0,0 +1,34 @@ +name: "šŸ› Report a bug" +description: "Report a problem on the website." +title: "[Bug]: " +labels: ["bug: unconfirmed"] +body: + - type: textarea + attributes: + label: Summary + description: | + A clear and concise summary of what the bug is. + placeholder: | + Example bug report: + When I click the "Submit" button on "Feedback", nothing happens. + validations: + required: true + - type: input + attributes: + label: Page + description: | + What page(s) did you encounter this bug on? + placeholder: | + https://react.dev/ + validations: + required: true + - type: textarea + attributes: + label: Details + description: | + Please provide any additional details about the bug. + placeholder: | + Example details: + The "Submit" button is unresponsive. I've tried refreshing the page and using a different browser, but the issue persists. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/1-typo.yml b/.github/ISSUE_TEMPLATE/1-typo.yml new file mode 100644 index 00000000..c86557a1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1-typo.yml @@ -0,0 +1,34 @@ +name: "šŸ¤¦ Typo or mistake" +description: "Report a typo or mistake in the docs." +title: "[Typo]: " +labels: ["type: typos"] +body: + - type: textarea + attributes: + label: Summary + description: | + A clear and concise summary of what the mistake is. + placeholder: | + Example: + The code example on the "useReducer" page includes an unused variable `nextId`. + validations: + required: true + - type: input + attributes: + label: Page + description: | + What page is the typo on? + placeholder: | + https://react.dev/ + validations: + required: true + - type: textarea + attributes: + label: Details + description: | + Please provide a explanation for why this is a mistake. + placeholder: | + Example mistake: + In the "useReducer" section of the "API Reference" page, the code example under "Writing a reducer function" includes an unused variable `nextId` that should be removed. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/2-suggestion.yml b/.github/ISSUE_TEMPLATE/2-suggestion.yml new file mode 100644 index 00000000..ac0b480f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/2-suggestion.yml @@ -0,0 +1,34 @@ +name: "šŸ’” Suggestions" +description: "Suggest a new page, section, or edit for an existing page." +title: "[Suggestion]: " +labels: ["type: documentation"] +body: + - type: textarea + attributes: + label: Summary + description: | + A clear and concise summary of what we should add. + placeholder: | + Example: + Add a new page for how to use React with TypeScript. + validations: + required: true + - type: input + attributes: + label: Page + description: | + What page is this about? + placeholder: | + https://react.dev/ + validations: + required: false + - type: textarea + attributes: + label: Details + description: | + Please provide a explanation for what you're suggesting. + placeholder: | + Example: + I think it would be helpful to have a page that explains how to use React with TypeScript. This could include a basic example of a component written in TypeScript, and a link to the TypeScript documentation. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/3-framework.yml b/.github/ISSUE_TEMPLATE/3-framework.yml new file mode 100644 index 00000000..a47295e1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/3-framework.yml @@ -0,0 +1,116 @@ +name: "šŸ“„ Suggest new framework" +description: "I am a framework author applying to be included as a recommended framework." +title: "[Framework]: " +labels: ["type: framework"] +body: + - type: markdown + attributes: + value: | + ## Apply to be included as a recommended React framework + + _This form is for framework authors to apply to be included as a recommended [React framework](https://react.dev/learn/start-a-new-react-project). If you are not a framework author, please contact the authors before submitting._ + + Our goal when recommending a framework is to start developers with a React project that solves common problems like code splitting, data fetching, routing, and HTML generation without any extra work later. We believe this will allow users to get started quickly with React, and scale their app to production. + + While we understand that many frameworks may want to be featured, this page is not a place to advertise every possible React framework or all frameworks that you can add React to. There are many great frameworks that offer support for React that are not listed in our guides. The frameworks we recommend have invested significantly in the React ecosystem, and collaborated with the React team to be compatible with our [full-stack React architecture vision](https://react.dev/learn/start-a-new-react-project#which-features-make-up-the-react-teams-full-stack-architecture-vision). + + To be included, frameworks must meet the following criteria: + + - **Free & open-source**: must be open source and free to use. + - **Well maintained**. must be actively maintained, providing bug fixes and improvements. + - **Active community**: must have a sufficiently large and active community to support users. + - **Clear onboarding**: must have clear install steps to install the React version of the framework. + - **Ecosystem compatibility**: must support using the full range of libraries and tools in the React ecosystem. + - **Self-hosting option**: must support an option to self-host applications without losing access to features. + - **Developer experience**. must allow developers to be productive by supporting features like Fast Refresh. + - **User experience**. must provide built-in support for common problems like routing and data-fetching. + - **Compatible with our future vision for React**. React evolves over time, and frameworks that do not align with Reactā€™s direction risk isolating their users from the main React ecosystem over time. To be included on this page we must feel confident that the framework is setting its users up for success with React over time. + + Please note, we have reviewed most of the popular frameworks available today, so it is unlikely we have not considered your framework already. But if you think we missed something, please complete the application below. + - type: input + attributes: + label: Name + description: | + What is the name of your framework? + validations: + required: true + - type: input + attributes: + label: Homepage + description: | + What is the URL of your homepage? + validations: + required: true + - type: input + attributes: + label: Install instructions + description: | + What is the URL of your getting started guide? + validations: + required: true + - type: dropdown + attributes: + label: Is your framework open source? + description: | + We only recommend free and open source frameworks. + options: + - 'No' + - 'Yes' + validations: + required: true + - type: textarea + attributes: + label: Well maintained + description: | + Please describe how your framework is actively maintained. Include recent releases, bug fixes, and improvements as examples. + validations: + required: true + - type: textarea + attributes: + label: Active community + description: | + Please describe your community. Include the size of your community, and links to community resources. + validations: + required: true + - type: textarea + attributes: + label: Clear onboarding + description: | + Please describe how a user can install your framework with React. Include links to any relevant documentation. + validations: + required: true + - type: textarea + attributes: + label: Ecosystem compatibility + description: | + Please describe any limitations your framework has with the React ecosystem. Include any libraries or tools that are not compatible with your framework. + validations: + required: true + - type: textarea + attributes: + label: Self-hosting option + description: | + Please describe how your framework supports self-hosting. Include any limitations to features when self-hosting. Also include whether you require a server to deploy your framework. + validations: + required: true + - type: textarea + attributes: + label: Developer Experience + description: | + Please describe how your framework provides a great developer experience. Include any limitations to React features like React DevTools, Chrome DevTools, and Fast Refresh. + validations: + required: true + - type: textarea + attributes: + label: User Experience + description: | + Please describe how your framework helps developers create high quality user experiences by solving common use-cases. Include specifics for how your framework offers built-in support for code-splitting, routing, HTML generation, and data-fetching in a way that avoids client/server waterfalls by default. Include details on how you offer features such as SSG and SSR. + validations: + required: true + - type: textarea + attributes: + label: Compatible with our future vision for React + description: | + Please describe how your framework aligns with our future vision for React. Include how your framework will evolve with React over time, and your plans to support future React features like React Server Components. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..63e310e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +contact_links: + - name: šŸ“ƒ Bugs in React + url: https://github.com/facebook/react/issues/new/choose + about: This issue tracker is not for bugs in React. Please file React issues here. + - name: šŸ¤” Questions and Help + url: https://reactjs.org/community/support.html + about: This issue tracker is not for support questions. Please refer to the React community's help and discussion forums. diff --git a/src/components/MDX/InlineCode.tsx b/src/components/MDX/InlineCode.tsx index d206e988..0e8db016 100644 --- a/src/components/MDX/InlineCode.tsx +++ b/src/components/MDX/InlineCode.tsx @@ -5,7 +5,8 @@ import cn from 'classnames'; interface InlineCodeProps { - isLink: boolean; + isLink?: boolean; + meta?: string; } function InlineCode({ isLink, diff --git a/src/components/MDX/MDXComponents.tsx b/src/components/MDX/MDXComponents.tsx index 67e78502..6790d361 100644 --- a/src/components/MDX/MDXComponents.tsx +++ b/src/components/MDX/MDXComponents.tsx @@ -19,6 +19,7 @@ import Link from './Link'; import {PackageImport} from './PackageImport'; import Recap from './Recap'; import Sandpack from './Sandpack'; +import SandpackWithHTMLOutput from './SandpackWithHTMLOutput'; import Diagram from './Diagram'; import DiagramGroup from './DiagramGroup'; import SimpleCallout from './SimpleCallout'; @@ -434,6 +435,7 @@ export const MDXComponents = { Recap, Recipes, Sandpack, + SandpackWithHTMLOutput, TeamMember, TerminalBlock, YouWillLearn, diff --git a/src/components/MDX/Sandpack/createFileMap.ts b/src/components/MDX/Sandpack/createFileMap.ts index 85c7f09b..615d34c9 100644 --- a/src/components/MDX/Sandpack/createFileMap.ts +++ b/src/components/MDX/Sandpack/createFileMap.ts @@ -11,7 +11,10 @@ export const SUPPORTED_FILES = [AppJSPath, StylesCSSPath]; export const createFileMap = (codeSnippets: any) => { return codeSnippets.reduce( (result: Record, codeSnippet: React.ReactElement) => { - if ((codeSnippet.type as any).mdxName !== 'pre') { + if ( + (codeSnippet.type as any).mdxName !== 'pre' && + codeSnippet.type !== 'pre' + ) { return result; } const {props} = codeSnippet.props.children; diff --git a/src/components/MDX/SandpackWithHTMLOutput.tsx b/src/components/MDX/SandpackWithHTMLOutput.tsx new file mode 100644 index 00000000..134da658 --- /dev/null +++ b/src/components/MDX/SandpackWithHTMLOutput.tsx @@ -0,0 +1,85 @@ +import {Children, memo} from 'react'; +import InlineCode from './InlineCode'; +import Sandpack from './Sandpack'; + +const ShowRenderedHTML = ` +import { renderToStaticMarkup } from 'react-dom/server'; +import formatHTML from './formatHTML.js'; + +export default function ShowRenderedHTML({children}) { + const markup = renderToStaticMarkup( + + + {children} + + ); + return ( + <> +

Rendered HTML:

+
+        {formatHTML(markup)}
+      
+ + ); +}`; + +const formatHTML = ` +import format from 'html-format'; + +export default function formatHTML(markup) { + // Cheap tricks to format the HTML readably -- haven't been able to + // find a package that runs in browser and prettifies the HTML if it + // lacks line-breaks. + return format(markup + .replace('', '\\n') + .replace('', '\\n') + .replaceAll(/<\\/script>/g, '<\\/script>\\n') + .replaceAll(/]*)\\/>/g, ' +``` + + + + + +--- + +## Reference {/*reference*/} + +### ` +``` + +[See more examples below.](#usage) + +#### Props {/*props*/} + +` + + ā€¦ + + + ); +} + +export default function App() { + return ( + + + + ); +} +``` + + diff --git a/src/content/reference/react-dom/components/title.md b/src/content/reference/react-dom/components/title.md new file mode 100644 index 00000000..9d6ed18c --- /dev/null +++ b/src/content/reference/react-dom/components/title.md @@ -0,0 +1,98 @@ +--- +title: "" +canary: true +--- + +<Canary> + +React's extensions to `<title>` are currently only available in React's canary and experimental channels. In stable releases of React `<title>` works only as a [built-in browser HTML component](https://react.dev/reference/react-dom/components#all-html-components). Learn more about [React's release channels here](/community/versioning-policy#all-release-channels). + +</Canary> + + +<Intro> + +The [built-in browser `<title>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title) lets you specify the title of the document. + +```js +<title>My Blog +``` + + + + + +--- + +## Reference {/*reference*/} + +### `` {/*title*/} + +To specify the title of the document, render the [built-in browser `<title>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title). You can render `<title>` from any component and React will always place the corresponding DOM element in the document head. + +```js +<title>My Blog +``` + +[See more examples below.](#usage) + +#### Props {/*props*/} + +`` supports all [common element props.](/reference/react-dom/components/common#props) + +* `children`: `<title>` accepts only text as a child. This text will become the title of the document. You can also pass your own components as long as they only render text. + +#### 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. + +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. + +<Pitfall> + +Only render a single `<title>` at a time. If more than one component renders a `<title>` tag at the same time, React will place all of those titles in the document head. When this happens, the behavior of browsers and search engines is undefined. + +</Pitfall> + +--- + +## Usage {/*usage*/} + +### Set the document title {/*set-the-document-title*/} + +Render the `<title>` component from any component with text as its children. React will put a `<title>` DOM node in the document `<head>`. + +<SandpackWithHTMLOutput> + +```js App.js active +import ShowRenderedHTML from './ShowRenderedHTML.js'; + +export default function ContactUsPage() { + return ( + <ShowRenderedHTML> + <title>My Site: Contact Us +

Contact Us

+

Email us at support@example.com

+ + ); +} +``` + + + +### Use variables in the title {/*use-variables-in-the-title*/} + +The children of the `` component must be a single string of text. (Or a single number or a single object with a `toString` method.) It might not be obvious, but using JSX curly braces like this: + +```js +<title>Results page {pageNumber} // šŸ”“ Problem: This is not a single string +``` + +... actually causes the `` component to get a two-element array as its children (the string `"Results page"` and the value of `pageNumber`). This will cause an error. Instead, use string interpolation to pass `<title>` a single string: + +```js +<title>{`Results page ${pageNumber}`} +``` + diff --git a/src/content/reference/react-dom/index.md b/src/content/reference/react-dom/index.md index fb5fd48b..80fd58fa 100644 --- a/src/content/reference/react-dom/index.md +++ b/src/content/reference/react-dom/index.md @@ -17,6 +17,19 @@ These APIs can be imported from your components. They are rarely used: * [`createPortal`](/reference/react-dom/createPortal) lets you render child components in a different part of the DOM tree. * [`flushSync`](/reference/react-dom/flushSync) lets you force React to flush a state update and update the DOM synchronously. +## Resource Preloading APIs {/*resource-preloading-apis*/} + +These APIs can be used to make apps faster by pre-loading resources such as scripts, stylesheets, and fonts as soon as you know you need them, for example before navigating to another page where the resources will be used. + +[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call these APIs yourself. Consult your framework's documentation for details. + +* [`prefetchDNS`](/reference/react-dom/prefetchDNS) lets you prefetch the IP address of a DNS domain name that you expect to connect to. +* [`preconnect`](/reference/react-dom/preconnect) lets you connect to a server you expect to request resources from, even if you don't know what resources you'll need yet. +* [`preload`](/reference/react-dom/preload) lets you fetch a stylesheet, font, image, or external script that you expect to use. +* [`preloadModule`](/reference/react-dom/preloadModule) lets you fetch an ESM module that you expect to use. +* [`preinit`](/reference/react-dom/preinit) lets you fetch and evaluate an external script or fetch and insert a stylesheet. +* [`preinitModule`](/reference/react-dom/preinitModule) lets you fetch and evaluate an ESM module. + --- ## Entry points {/*entry-points*/} diff --git a/src/content/reference/react-dom/preconnect.md b/src/content/reference/react-dom/preconnect.md new file mode 100644 index 00000000..cb14a5e8 --- /dev/null +++ b/src/content/reference/react-dom/preconnect.md @@ -0,0 +1,96 @@ +--- +title: preconnect +canary: true +--- + + + +The `preconnect` function 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). + + + + + +`preconnect` lets you eagerly connect to a server that you expect to load resources from. + +```js +preconnect("https://example.com"); +``` + + + + + +--- + +## Reference {/*reference*/} + +### `preconnect(href)` {/*preconnect*/} + +To preconnect to a host, call the `preconnect` function from `react-dom`. + +```js +import { preconnect } from 'react-dom'; + +function AppRoot() { + preconnect("https://example.com"); + // ... +} + +``` + +[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. + +#### Parameters {/*parameters*/} + +* `href`: a string. The URL of the server you want to connect to. + + +#### Returns {/*returns*/} + +`preconnect` returns nothing. + +#### Caveats {/*caveats*/} + +* Multiple calls to `preconnect` with the same server have the same effect as a single call. +* In the browser, you can call `preconnect` in any situation: while rendering a component, in an effect, in an event handler, and so on. +* In server-side rendering or when rendering Server Components, `preconnect` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. +* If you know the specific resources you'll need, you can call [other functions](/reference/react-dom/#resource-preloading-apis) instead that will start loading the resources right away. +* There is no benefit to preconnecting to the same server the webpage itself is hosted from because it's already been connected to by the time the hint would be given. + +--- + +## Usage {/*usage*/} + +### Preconnecting when rendering {/*preconnecting-when-rendering*/} + +Call `preconnect` when rendering a component if you know that its children will load external resources from that host. + +```js +import { preconnect } from 'react-dom'; + +function AppRoot() { + preconnect("https://example.com"); + return ...; +} +``` + +### Preconnecting in an event handler {/*preconnecting-in-an-event-handler*/} + +Call `preconnect` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. + +```js +import { preconnect } from 'react-dom'; + +function CallToAction() { + const onClick = () => { + preconnect('http://example.com'); + startWizard(); + } + return ( + + ); +} +``` diff --git a/src/content/reference/react-dom/prefetchDNS.md b/src/content/reference/react-dom/prefetchDNS.md new file mode 100644 index 00000000..f9889836 --- /dev/null +++ b/src/content/reference/react-dom/prefetchDNS.md @@ -0,0 +1,96 @@ +--- +title: prefetchDNS +canary: true +--- + + + +The `prefetchDNS` function 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). + + + + + +`prefetchDNS` lets you eagerly look up the IP of a server that you expect to load resources from. + +```js +prefetchDNS("https://example.com"); +``` + + + + + +--- + +## Reference {/*reference*/} + +### `prefetchDNS(href)` {/*prefetchdns*/} + +To look up a host, call the `prefetchDNS` function from `react-dom`. + +```js +import { prefetchDNS } from 'react-dom'; + +function AppRoot() { + prefetchDNS("https://example.com"); + // ... +} + +``` + +[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. + +#### Parameters {/*parameters*/} + +* `href`: a string. The URL of the server you want to connect to. + +#### Returns {/*returns*/} + +`prefetchDNS` returns nothing. + +#### Caveats {/*caveats*/} + +* Multiple calls to `prefetchDNS` with the same server have the same effect as a single call. +* In the browser, you can call `prefetchDNS` in any situation: while rendering a component, in an effect, in an event handler, and so on. +* In server-side rendering or when rendering Server Components, `prefetchDNS` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. +* If you know the specific resources you'll need, you can call [other functions](/reference/react-dom/#resource-preloading-apis) instead that will start loading the resources right away. +* There is no benefit to prefetching the same server the webpage itself is hosted from because it's already been looked up by the time the hint would be given. +* Compared with [`preconnect`](/reference/react-dom/preconnect), `prefetchDNS` may be better if you are speculatively connecting to a large number of domains, in which case the overhead of preconnections might outweigh the benefit. + +--- + +## Usage {/*usage*/} + +### Prefetching DNS when rendering {/*prefetching-dns-when-rendering*/} + +Call `prefetchDNS` when rendering a component if you know that its children will load external resources from that host. + +```js +import { prefetchDNS } from 'react-dom'; + +function AppRoot() { + prefetchDNS("https://example.com"); + return ...; +} +``` + +### Prefetching DNS in an event handler {/*prefetching-dns-in-an-event-handler*/} + +Call `prefetchDNS` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. + +```js +import { prefetchDNS } from 'react-dom'; + +function CallToAction() { + const onClick = () => { + prefetchDNS('http://example.com'); + startWizard(); + } + return ( + + ); +} +``` diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md new file mode 100644 index 00000000..5a04528b --- /dev/null +++ b/src/content/reference/react-dom/preinit.md @@ -0,0 +1,133 @@ +--- +title: preinit +canary: true +--- + + + +The `preinit` function 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). + + + + + +[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. + + + + + +`preinit` lets you eagerly fetch and evaluate a stylesheet or external script. + +```js +preinit("https://example.com/script.js", {as: "style"}); +``` + + + + + +--- + +## Reference {/*reference*/} + +### `preinit(href, options)` {/*preinit*/} + +To preinit a script or stylesheet, call the `preinit` function from `react-dom`. + +```js +import { preinit } from 'react-dom'; + +function AppRoot() { + preinit("https://example.com/script.js", {as: "script"}); + // ... +} + +``` + +[See more examples below.](#usage) + +The `preinit` function provides the browser with a hint that it should start downloading and executing the given resource, which can save time. Scripts that you `preinit` are executed when they finish downloading. Stylesheets that you preinit are inserted into the document, which causes them to go into effect right away. + +#### Parameters {/*parameters*/} + +* `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`. + * `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`. It is required when `as` is set to `"fetch"`. + * `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. + * `fetchPriority`: a string. Suggests a relative priority for fetching the resource. The possible values are `auto` (the default), `high`, and `low`. + +#### Returns {/*returns*/} + +`preinit` returns nothing. + +#### Caveats {/*caveats*/} + +* Multiple calls to `preinit` with the same `href` have the same effect as a single call. +* In the browser, you can call `preinit` in any situation: while rendering a component, in an effect, in an event handler, and so on. +* In server-side rendering or when rendering Server Components, `preinit` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. + +--- + +## Usage {/*usage*/} + +### Preiniting when rendering {/*preiniting-when-rendering*/} + +Call `preinit` when rendering a component if you know that it or its children will use a specific resource, and you're OK with the resource being evaluated and thereby taking effect immediately upon being downloaded. + + + +#### Preiniting an external script {/*preiniting-an-external-script*/} + +```js +import { preinit } from 'react-dom'; + +function AppRoot() { + preinit("https://example.com/script.js", {as: "script"}); + return ...; +} +``` + +If you want the browser to download the script but not to execute it right away, use [`preload`](/reference/react-dom/preload) instead. If you want to load an ESM module, use [`preinitModule`](/reference/react-dom/preinitModule). + + + +#### Preiniting a stylesheet {/*preiniting-a-stylesheet*/} + +```js +import { preinit } from 'react-dom'; + +function AppRoot() { + preinit("https://example.com/style.css", {as: "style", precedence: "medium"}); + return ...; +} +``` + +The `precedence` option, which is required, lets you control the order of stylesheets within the document. Stylesheets with higher precedence can overrule those with lower precedence. + +If you want to download the stylesheet but not to insert it into the document right away, use [`preload`](/reference/react-dom/preload) instead. + + + + + +### Preiniting in an event handler {/*preiniting-in-an-event-handler*/} + +Call `preinit` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. + +```js +import { preinit } from 'react-dom'; + +function CallToAction() { + const onClick = () => { + preinit("https://example.com/wizardStyles.css", {as: "style"}); + startWizard(); + } + return ( + + ); +} +``` diff --git a/src/content/reference/react-dom/preinitModule.md b/src/content/reference/react-dom/preinitModule.md new file mode 100644 index 00000000..ba6316a7 --- /dev/null +++ b/src/content/reference/react-dom/preinitModule.md @@ -0,0 +1,106 @@ +--- +title: preinitModule +canary: true +--- + + + +The `preinitModule` function 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). + + + + + +[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. + + + + + +`preinitModule` lets you eagerly fetch and evaluate an ESM module. + +```js +preinitModule("https://example.com/module.js", {as: "script"}); +``` + + + + + +--- + +## Reference {/*reference*/} + +### `preinitModule(href, options)` {/*preinitmodule*/} + +To preinit an ESM module, call the `preinitModule` function from `react-dom`. + +```js +import { preinitModule } from 'react-dom'; + +function AppRoot() { + preinitModule("https://example.com/module.js", {as: "script"}); + // ... +} + +``` + +[See more examples below.](#usage) + +The `preinitModule` function provides the browser with a hint that it should start downloading and executing the given module, which can save time. Modules that you `preinit` are executed when they finish downloading. + +#### Parameters {/*parameters*/} + +* `href`: a string. The URL of the module you want to download and exeucute. +* `options`: an object. It contains the following properties: + * `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. + +#### Returns {/*returns*/} + +`preinitModule` returns nothing. + +#### Caveats {/*caveats*/} + +* Multiple calls to `preinitModule` with the same `href` have the same effect as a single call. +* In the browser, you can call `preinitModule` in any situation: while rendering a component, in an effect, in an event handler, and so on. +* In server-side rendering or when rendering Server Components, `preinitModule` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. + +--- + +## Usage {/*usage*/} + +### Preloading when rendering {/*preloading-when-rendering*/} + +Call `preinitModule` when rendering a component if you know that it or its children will use a specific module and you're OK with the module being evaluated and thereby taking effect immediately upon being downloaded. + +```js +import { preinitModule } from 'react-dom'; + +function AppRoot() { + preinitModule("https://example.com/module.js", {as: "script"}); + return ...; +} +``` + +If you want the browser to download the module but not to execute it right away, use [`preloadModule`](/reference/react-dom/preloadModule) instead. If you want to preinit a script that isn't an ESM module, use [`preinit`](/reference/react-dom/preinit). + +### Preloading in an event handler {/*preloading-in-an-event-handler*/} + +Call `preinitModule` in an event handler before transitioning to a page or state where the module will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. + +```js +import { preinitModule } from 'react-dom'; + +function CallToAction() { + const onClick = () => { + preinitModule("https://example.com/module.js", {as: "script"}); + startWizard(); + } + return ( + + ); +} +``` diff --git a/src/content/reference/react-dom/preload.md b/src/content/reference/react-dom/preload.md new file mode 100644 index 00000000..ffec1177 --- /dev/null +++ b/src/content/reference/react-dom/preload.md @@ -0,0 +1,171 @@ +--- +title: preload +canary: true +--- + + + +The `preload` function 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). + + + + + +[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. + + + + + +`preload` lets you eagerly fetch a resource such as a stylesheet, font, or external script that you expect to use. + +```js +preload("https://example.com/font.woff2", {as: "font"}); +``` + + + + + +--- + +## Reference {/*reference*/} + +### `preload(href, options)` {/*preload*/} + +To preload a resource, call the `preload` function from `react-dom`. + +```js +import { preload } from 'react-dom'; + +function AppRoot() { + preload("https://example.com/font.woff2", {as: "font"}); + // ... +} + +``` + +[See more examples below.](#usage) + +The `preload` function provides the browser with a hint that it should start downloading the given resource, which can save time. + +#### Parameters {/*parameters*/} + +* `href`: a string. The URL of the resource you want to download. +* `options`: an object. It contains the following properties: + * `as`: a required string. The type of resource. Its [possible values](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#as) are `audio`, `document`, `embed`, `fetch`, `font`, `image`, `object`, `script`, `style`, `track`, `video`, `worker`. + * `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`. It is required when `as` is set to `"fetch"`. + * `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. + * `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). + +#### Returns {/*returns*/} + +`preload` returns nothing. + +#### Caveats {/*caveats*/} + +* Multiple equivalent calls to `preload` have the same effect as a single call. Calls to `preload` are considered equivalent according to the following rules: + * Two calls are equivalent if they have the same `href`, except: + * If `as` is set to `image`, two calls are equivalent if they have the same `href`, `imageSrcSet`, and `imageSizes`. +* In the browser, you can call `preload` in any situation: while rendering a component, in an effect, in an event handler, and so on. +* In server-side rendering or when rendering Server Components, `preload` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. + +--- + +## Usage {/*usage*/} + +### Preloading when rendering {/*preloading-when-rendering*/} + +Call `preload` when rendering a component if you know that it or its children will use a specific resource. + + + +#### Preloading an external script {/*preloading-an-external-script*/} + +```js +import { preload } from 'react-dom'; + +function AppRoot() { + preload("https://example.com/script.js", {as: "script"}); + return ...; +} +``` + +If you want the browser to start executing the script immediately (rather than just downloading it), use [`preinit`](/reference/react-dom/preinit) instead. If you want to load an ESM module, use [`preloadModule`](/reference/react-dom/preloadModule). + + + +#### Preloading a stylesheet {/*preloading-a-stylesheet*/} + +```js +import { preload } from 'react-dom'; + +function AppRoot() { + preload("https://example.com/style.css", {as: "style"}); + return ...; +} +``` + +If you want the stylesheet to be inserted into the document immediately (which means the browser will start parsing it immediately rather than just downloading it), use [`preinit`](/reference/react-dom/preinit) instead. + + + +#### Preloading a font {/*preloading-a-font*/} + +```js +import { preload } from 'react-dom'; + +function AppRoot() { + preload("https://example.com/style.css", {as: "style"}); + preload("https://example.com/font.woff2", {as: "font"}); + return ...; +} +``` + +If you preload a stylesheet, it's smart to also preload any fonts that the stylesheet refers to. That way, the browser can start downloading the font before it's downloaded and parsed the stylesheet. + + + +#### Preloading an image {/*preloading-an-image*/} + +```js +import { preload } from 'react-dom'; + +function AppRoot() { + preload("/banner.png", { + as: "image", + imageSrcSet: "/banner512.png 512w, /banner1024.png 1024w", + imageSizes: "(max-width: 512px) 512px, 1024px", + }); + return ...; +} +``` + +When preloading an image, the `imageSrcSet` and `imageSizes` options help the browser [fetch the correctly sized image for the size of the screen]((https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images)). + + + + + +### Preloading in an event handler {/*preloading-in-an-event-handler*/} + +Call `preload` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. + +```js +import { preload } from 'react-dom'; + +function CallToAction() { + const onClick = () => { + preload("https://example.com/wizardStyles.css", {as: "style"}); + startWizard(); + } + return ( + + ); +} +``` diff --git a/src/content/reference/react-dom/preloadModule.md b/src/content/reference/react-dom/preloadModule.md new file mode 100644 index 00000000..05333f1c --- /dev/null +++ b/src/content/reference/react-dom/preloadModule.md @@ -0,0 +1,107 @@ +--- +title: preloadModule +canary: true +--- + + + +The `preloadModule` function 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). + + + + + +[React-based frameworks](/learn/start-a-new-react-project) frequently handle resource loading for you, so you might not have to call this API yourself. Consult your framework's documentation for details. + + + + + +`preloadModule` lets you eagerly fetch an ESM module that you expect to use. + +```js +preloadModule("https://example.com/module.js", {as: "script"}); +``` + + + + + +--- + +## Reference {/*reference*/} + +### `preloadModule(href, options)` {/*preloadmodule*/} + +To preload an ESM module, call the `preloadModule` function from `react-dom`. + +```js +import { preloadModule } from 'react-dom'; + +function AppRoot() { + preloadModule("https://example.com/module.js", {as: "script"}); + // ... +} + +``` + +[See more examples below.](#usage) + +The `preloadModule` function provides the browser with a hint that it should start downloading the given module, which can save time. + +#### Parameters {/*parameters*/} + +* `href`: a string. The URL of the module you want to download. +* `options`: an object. It contains the following properties: + * `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. + + +#### Returns {/*returns*/} + +`preloadModule` returns nothing. + +#### Caveats {/*caveats*/} + +* Multiple calls to `preloadModule` with the same `href` have the same effect as a single call. +* In the browser, you can call `preloadModule` in any situation: while rendering a component, in an effect, in an event handler, and so on. +* In server-side rendering or when rendering Server Components, `preloadModule` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. + +--- + +## Usage {/*usage*/} + +### Preloading when rendering {/*preloading-when-rendering*/} + +Call `preloadModule` when rendering a component if you know that it or its children will use a specific module. + +```js +import { preloadModule } from 'react-dom'; + +function AppRoot() { + preloadModule("https://example.com/module.js", {as: "script"}); + return ...; +} +``` + +If you want the browser to start executing the module immediately (rather than just downloading it), use [`preinitModule`](/reference/react-dom/preinitModule) instead. If you want to load a script that isn't an ESM module, use [`preload`](/reference/react-dom/preload). + +### Preloading in an event handler {/*preloading-in-an-event-handler*/} + +Call `preloadModule` in an event handler before transitioning to a page or state where the module will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. + +```js +import { preloadModule } from 'react-dom'; + +function CallToAction() { + const onClick = () => { + preloadModule("https://example.com/module.js", {as: "script"}); + startWizard(); + } + return ( + + ); +} +``` diff --git a/src/sidebarReference.json b/src/sidebarReference.json index 5a655655..da153adc 100644 --- a/src/sidebarReference.json +++ b/src/sidebarReference.json @@ -219,6 +219,31 @@ { "title": "