`.
- En général, vous utiliserez les refs pour des actions non destructrices telles que la gestion du focus, le défilement ou la mesure des dimensions et positions d'éléments du DOM.
- Un composant n'expose pas, par défaut, ses nœuds DOM. Vous pouvez choisir d'en exposer un en utilisant `forwardRef` et en passant le second argument `ref` de la fonction de rappel au nœud désiré.
- Évitez de modifier les nœuds DOM gérés par React. Si vous devez absolument le faire, limitez-vous aux parties que React n'a aucune raison de mettre à jour.
+=======
+- Refs are a generic concept, but most often you'll use them to hold DOM elements.
+- You instruct React to put a DOM node into `myRef.current` by passing `
`.
+- Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements.
+- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using the `ref` prop.
+- Avoid changing DOM nodes managed by React.
+- If you do modify DOM nodes managed by React, modify parts that React has no reason to update.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -1119,7 +1173,11 @@ Faites en sorte qu'un clic sur le bouton « Recherche » donne le focus au cha
+<<<<<<< HEAD
Vous aurez besoin de `forwardRef` pour choisir d'exposer un nœud DOM pour votre propre composant `SearchInput`.
+=======
+You'll need to pass `ref` as a prop to opt into exposing a DOM node from your own component like `SearchInput`.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -1204,6 +1262,7 @@ export default function SearchButton({ onClick }) {
```
```js src/SearchInput.js
+<<<<<<< HEAD
import { forwardRef } from 'react';
export default forwardRef(
@@ -1216,6 +1275,16 @@ export default forwardRef(
);
}
);
+=======
+export default function SearchInput({ ref }) {
+ return (
+
+ );
+}
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
```
```css
diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md
index 197f0da92..dce7d34cc 100644
--- a/src/content/learn/passing-data-deeply-with-context.md
+++ b/src/content/learn/passing-data-deeply-with-context.md
@@ -468,15 +468,19 @@ import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
);
}
```
+<<<<<<< HEAD
React le comprend ainsi : « si un composant à l'intérieur de `
` demande `LevelContext`, alors donne-lui ce `level` ». Le composant utilisera la valeur du `` le plus proche dans l'arbre au-dessus de lui.
+=======
+This tells React: "if any component inside this `` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -514,9 +518,9 @@ import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
);
}
@@ -566,9 +570,15 @@ export const LevelContext = createContext(1);
Le résultat est le même qu'avec le code d'origine, mais vous n'avez plus besoin de transmettre la prop `level` à chaque composant `Heading`. Au lieu de ça, il « détermine » son niveau d'en-tête en interrogeant la `Section` la plus proche :
+<<<<<<< HEAD
1. Vous passez une prop `level` à la ``.
2. `Section` enrobe ses enfants dans un ``.
3. `Heading` demande la valeur la plus proche de `LevelContext` avec `useContext(LevelContext)`.
+=======
+1. You pass a `level` prop to the ``.
+2. `Section` wraps its children into ``.
+3. `Heading` asks the closest value of `LevelContext` above with `useContext(LevelContext)`.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
## Utiliser et fournir le contexte depuis le même composant {/*using-and-providing-context-from-the-same-component*/}
@@ -595,9 +605,9 @@ export default function Section({ children }) {
const level = useContext(LevelContext);
return (
);
}
@@ -643,9 +653,9 @@ export default function Section({ children }) {
const level = useContext(LevelContext);
return (
);
}
@@ -776,9 +786,9 @@ export default function Section({ children, isFancy }) {
'section ' +
(isFancy ? 'fancy' : '')
}>
-
+
{children}
-
+
);
}
@@ -864,6 +874,7 @@ D'une manière générale, si certaines informations sont nécessaires pour des
+<<<<<<< HEAD
* Le contexte permet à un composant de fournir certaines informations à l'ensemble de l'arbre situé en dessous de lui.
* Pour transmettre un contexte :
1. Créez-le et exportez-le avec `export const MyContext = createContext(defaultValue)`.
@@ -872,6 +883,16 @@ D'une manière générale, si certaines informations sont nécessaires pour des
* Le contexte traverse tous les composants intermédiaires.
* Le contexte vous permet d'écrire des composants qui « s'adaptent à leur environnement ».
* Avant d'utiliser un contexte, essayez de passer par les props ou en mettant du JSX dans les `children`.
+=======
+* Context lets a component provide some information to the entire tree below it.
+* To pass context:
+ 1. Create and export it with `export const MyContext = createContext(defaultValue)`.
+ 2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep.
+ 3. Wrap children into `` to provide it from a parent.
+* Context passes through any components in the middle.
+* Context lets you write components that "adapt to their surroundings".
+* Before you use context, try passing props or passing JSX as `children`.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -1022,7 +1043,11 @@ li {
Retirez la prop `imageSize` de tous les composants.
+<<<<<<< HEAD
Créez et exportez `ImageSizeContext` depuis `Context.js`. Ensuite, enrobez la `List` dans `` pour propager la valeur vers le bas, puis `useContext(ImageSizeContext)` pour la lire dans `PlaceImage` :
+=======
+Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`:
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -1036,7 +1061,7 @@ export default function App() {
const [isLarge, setIsLarge] = useState(false);
const imageSize = isLarge ? 150 : 100;
return (
-
-
+
)
}
diff --git a/src/content/learn/react-compiler.md b/src/content/learn/react-compiler.md
index 7d830d241..8bd7a4e34 100644
--- a/src/content/learn/react-compiler.md
+++ b/src/content/learn/react-compiler.md
@@ -326,7 +326,11 @@ export default defineConfig({
### Webpack {/*usage-with-webpack*/}
+<<<<<<< HEAD
Un chargeur Webpack maintenu par la communauté est [désormais disponible ici](https://github.com/SukkaW/react-compiler-webpack).
+=======
+A community webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
### Expo {/*usage-with-expo*/}
@@ -362,7 +366,11 @@ React Compiler peut vérifier statiquement la plupart des Règles de React, et
### Comment savoir si mes composants ont été optimisés ? {/*how-do-i-know-my-components-have-been-optimized*/}
+<<<<<<< HEAD
[React Devtools](/learn/react-developer-tools) (v5.0+) prend nativement en charge React Compiler et affichera un badge « Memo ✨ » à côté des composants qui ont été optimisés par le compilateur.
+=======
+[React DevTools](/learn/react-developer-tools) (v5.0+) and [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) have built-in support for React Compiler and will display a "Memo ✨" badge next to components that have been optimized by the compiler.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
### Quelque chose ne fonctionne plus après la compilation {/*something-is-not-working-after-compilation*/}
diff --git a/src/content/learn/react-developer-tools.md b/src/content/learn/react-developer-tools.md
index f19187126..b172e0fac 100644
--- a/src/content/learn/react-developer-tools.md
+++ b/src/content/learn/react-developer-tools.md
@@ -52,6 +52,7 @@ Pour finir, rafraîchissez votre page dans le navigateur pour l'afficher dans le

+<<<<<<< HEAD
## Mobile natif (React Native) {/*mobile-react-native*/}
Les outils de développement React peuvent également être utilisés pour inspecter les applis construites avec [React Native](https://reactnative.dev/).
@@ -59,11 +60,15 @@ La façon la plus simple d'utiliser les outils de développement React consiste
```bash
# Yarn
yarn global add react-devtools
+=======
+## Mobile (React Native) {/*mobile-react-native*/}
-# Npm
-npm install -g react-devtools
-```
+To inspect apps built with [React Native](https://reactnative.dev/), you can use [React Native DevTools](https://reactnative.dev/docs/react-native-devtools), the built-in debugger that deeply integrates React Developer Tools. All features work identically to the browser extension, including native element highlighting and selection.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
+
+[Learn more about debugging in React Native.](https://reactnative.dev/docs/debugging)
+<<<<<<< HEAD
Ouvrez alors les outils de développement depuis le terminal :
```bash
react-devtools
@@ -74,3 +79,6 @@ react-devtools
> Essayez de relancer l'appli si les outils de développement ne se connectent toujours pas au bout de quelques secondes.
[En apprendre plus sur le débogage de React Native](https://reactnative.dev/docs/debugging).
+=======
+> For versions of React Native earlier than 0.76, please use the standalone build of React DevTools by following the [Safari and other browsers](#safari-and-other-browsers) guide above.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
diff --git a/src/content/learn/render-and-commit.md b/src/content/learn/render-and-commit.md
index e83b99e31..e47042c59 100644
--- a/src/content/learn/render-and-commit.md
+++ b/src/content/learn/render-and-commit.md
@@ -70,9 +70,15 @@ Essayez de commenter l'appel à `root.render()` pour voir votre composant dispar
Une fois que le composant a fait son rendu initial, vous pouvez déclencher des rendus supplémentaires en mettant à jour son état au moyen d'une [fonction `set`](/reference/react/useState#setstate). Mettre à jour l'état local d'un composant met automatiquement un rendu en file d'attente. (C'est un peu comme le convive d'un restaurant qui commanderait du thé, un dessert et plein d'autres choses après avoir passé sa commande initiale, en fonction de l'état de sa faim et de sa soif.)
+<<<<<<< HEAD
+=======
+
+
+
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
## Étape 2 : rendu des composants par React {/*step-2-react-renders-your-components*/}
@@ -84,7 +90,11 @@ Après que vous avez déclenché un rendu, React appelle vos composants pour dé
Ce processus est récursif : si le composant mis à jour renvoie un autre composant, React fera le rendu de *ce* composant-là ensuite, et si ce dernier renvoie à son tour un autre composant, il fera le rendu de *ce* composant-là, et ainsi de suite. Le processus continue jusqu'à ce qu'il ne reste plus de composants imbriqués à traiter, pour que React sache exactement ce qu'il doit afficher à l'écran.
+<<<<<<< HEAD
Dans l'exemple qui suit, React appellera `Gallery()`, puis plusieurs fois `Image()` :
+=======
+In the following example, React will call `Gallery()` and `Image()` several times:
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -148,10 +158,17 @@ Le comportement par défaut, qui fait le rendu de tous les composants enveloppé
## Étape 3 : commit dans le DOM par React {/*step-3-react-commits-changes-to-the-dom*/}
+<<<<<<< HEAD
Après avoir fait le rendu de vos composants (c'est-à-dire après avoir appelé leurs fonctions), React devra mettre à jour le DOM.
- **Lors du rendu initial**, React utilisera l'API DOM [`appendChild()`](https://developer.mozilla.org/fr/docs/Web/API/Node/appendChild) pour retranscrire à l'écran tous les nœuds DOM qu'il a créés.
- **Lors des rendus ultérieurs**, React s'attachera à effectuer le strict minimum d'opérations nécessaires (qu'il aura déterminées lors de la phase de rendu !) pour mettre le DOM en correspondance avec le résultat du dernier rendu en date.
+=======
+After rendering (calling) your components, React will modify the DOM.
+
+* **For the initial render,** React will use the [`appendChild()`](https://developer.mozilla.org/docs/Web/API/Node/appendChild) DOM API to put all the DOM nodes it has created on screen.
+* **For re-renders,** React will apply the minimal necessary operations (calculated while rendering!) to make the DOM match the latest rendering output.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
**React ne modifie les nœuds DOM que s'il y a un écart d'un rendu à l'autre.** Par exemple, voici un composant qui refait son rendu avec des props différentes passées depuis son parent à chaque seconde. Remarquez que vous pouvez ajouter du texte dans l'``, modifier sa `value`, mais le texte ne disparaît pas quand le composant refait son rendu :
diff --git a/src/content/learn/setup.md b/src/content/learn/setup.md
new file mode 100644
index 000000000..2c46ee148
--- /dev/null
+++ b/src/content/learn/setup.md
@@ -0,0 +1,28 @@
+---
+title: Setup
+---
+
+
+React integrates with tools like editors, TypeScript, browser extensions, and compilers. This section will help you get your environment set up.
+
+
+
+## Editor Setup {/*editor-setup*/}
+
+See our [recommended editors](/learn/editor-setup) and learn how to set them up to work with React.
+
+## Using TypeScript {/*using-typescript*/}
+
+TypeScript is a popular way to add type definitions to JavaScript codebases. [Learn how to integrate TypeScript into your React projects](/learn/typescript).
+
+## React Developer Tools {/*react-developer-tools*/}
+
+React Developer Tools is a browser extension that can inspect React components, edit props and state, and identify performance problems. Learn how to install it [here](learn/react-developer-tools).
+
+## React Compiler {/*react-compiler*/}
+
+React Compiler is a tool that automatically optimizes your React app. [Learn more](/learn/react-compiler).
+
+## Next steps {/*next-steps*/}
+
+Head to the [Quick Start](/learn) guide for a tour of the most important React concepts you will encounter every day.
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index 7bfaeaf36..8f563267d 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -1450,7 +1450,11 @@ Si votre *linter* est [configuré pour React](/learn/editor-setup#linting), vous
#### Retirer l'état superflu {/*remove-unnecessary-state*/}
+<<<<<<< HEAD
Dans cet exemple, cliquer sur le bouton devrait demander à l'utilisateur son nom et le saluer dans une alerte. Vous avez essayé de recourir à un état pour vous souvenir du nom, mais pour une raison ou une autre ça affiche toujours « Bonjour ! ».
+=======
+When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason the first time it shows "Hello, !", and then "Hello, [name]!" with the previous input every time after.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
Pour corriger ce code, retirez la variable d'état superflue. (Nous explorerons les [raisons de ce problème](/learn/state-as-a-snapshot) prochainement.)
diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md
index 79a2f023f..884144c5e 100644
--- a/src/content/learn/tutorial-tic-tac-toe.md
+++ b/src/content/learn/tutorial-tic-tac-toe.md
@@ -297,7 +297,11 @@ export default function Square() {
}
```
+<<<<<<< HEAD
La section _browser_ devrait afficher un carré avec un X à l'intérieur, comme ceci :
+=======
+The _browser_ section should be displaying a square with an X in it like this:
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff

@@ -1333,7 +1337,11 @@ Récapitulons ce qui se passe techniquement lorsque l'utilisateur clique sur la
2. `handleClick` utilise son argument (`0`) pour mettre à jour le premier élément du tableau `squares`, le faisant passer de `null` à `X`.
3. L'état `squares` du composant `Board` est mis à jour, du coup `Board` et tous ses enfants refont leur rendu. Ça modifie la prop `value` du composant `Square` d'index `0` pour la passer de `null` à `X`.
+<<<<<<< HEAD
Au final l'utilisateur voit que la case supérieure gauche a changé après qu'il a cliqué dessus : elle est passée du vide à un `X`.
+=======
+In the end the user sees that the upper left square has changed from empty to having an `X` after clicking it.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -1414,7 +1422,11 @@ Mais attendez une minute, il y a un problème : essayez de cliquer plusieurs fo
Le `X` est écrasé par un `O` ! Même si ça pourrait constituer une variante intéressante du jeu, nous allons nous en tenir aux règles conventionnelles.
+<<<<<<< HEAD
Lorsque vous marquez une case avec un `X` ou un `O`, vous ne vérifiez pas d'abord si la case a déjà une valeur `X` ou `O`. Vous pouvez corriger ça en faisant un *retour anticipé*. Vérifiez si la case a déjà un `X` ou un `O`. Si la case est déjà remplie, faites un `return` tôt dans la fonction `handleClick`, avant qu'elle ne tente de mettre à jour l'état du plateau.
+=======
+When you mark a square with an `X` or an `O` you aren't first checking to see if the square already has an `X` or `O` value. You can fix this by *returning early*. You'll check to see if the square already has an `X` or an `O`. If the square is already filled, you will `return` in the `handleClick` function early--before it tries to update the board state.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
```js {2,3,4}
function handleClick(i) {
@@ -1564,7 +1576,11 @@ Peu importe que vous définissiez `calculateWinner` avant ou après `Board`. Me
+<<<<<<< HEAD
Vous appellerez `calculateWinner(squares)` dans la fonction `handleClick` du composant `Board` pour vérifier si un joueur a gagné. Vous pouvez effectuer cette vérification au même endroit que celle pour une case déjà remplie. Dans les deux cas, nous souhaitons un retour anticipé :
+=======
+You will call `calculateWinner(squares)` in the `Board` component's `handleClick` function to check if a player has won. You can perform this check at the same time you check if a user has clicked a square that already has an `X` or an `O`. We'd like to return early in both cases:
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
```js {2}
function handleClick(i) {
diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md
index 6f761b035..27538857b 100644
--- a/src/content/reference/react-dom/client/createRoot.md
+++ b/src/content/reference/react-dom/client/createRoot.md
@@ -49,7 +49,14 @@ Une appli entièrement construite en React n'aura généralement qu'un appel à
* `onRecoverableError` **optionnelle** : fonction de rappel appelée lorsque React retombe automatiquement sur ses pieds suite à une erreur. Appelée avec l’`error` levée par React et un objet `errorInfo` contenant la `componentStack`. Certaines de ces erreurs peuvent exposer leur cause originelle dans `error.cause`.
* `identifierPrefix` **optionnel** : un préfixe textuel utilisé pour les ID générés par [`useId`](/reference/react/useId). Pratique pour éviter les conflits entre les ID au sein de racines multiples sur une même page.
+<<<<<<< HEAD
#### Valeur renvoyée {/*returns*/}
+=======
+ * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`.
+ * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown, and an `errorInfo` object containing the `componentStack`.
+ * **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with an `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`.
+ * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
`createRoot` renvoie un objet avec deux méthodes : [`render`](#root-render) et [`unmount`](#root-unmount).
@@ -141,7 +148,7 @@ En général, vous n'aurez besoin de ce code qu'une fois, au démarrage. Il va
-```html index.html
+```html public/index.html
Mon appli
@@ -341,10 +348,15 @@ export default function App({counter}) {
Il est toutefois rare d'appeler `render` plusieurs fois. En général, vos composants [mettront plutôt à jour l'état](/reference/react/useState).
+<<<<<<< HEAD
### Afficher un dialogue lors d'erreurs non capturées {/*show-a-dialog-for-uncaught-errors*/}
+=======
+### Error logging in production {/*error-logging-in-production*/}
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
-
+By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`:
+<<<<<<< HEAD
`onUncaughtError` n'est disponible que dans la dernière version React Canary.
@@ -788,16 +800,22 @@ import { createRoot } from "react-dom/client";
import App from "./App.js";
import {reportCaughtError} from "./reportError";
import "./styles.css";
+=======
+```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]]
+import { createRoot } from "react-dom/client";
+import { reportCaughtError } from "./reportError";
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
const container = document.getElementById("root");
const root = createRoot(container, {
onCaughtError: (error, errorInfo) => {
- if (error.message !== 'Known error') {
+ if (error.message !== "Known error") {
reportCaughtError({
- error,
+ error,
componentStack: errorInfo.componentStack,
});
}
+<<<<<<< HEAD
}
});
root.render();
@@ -867,13 +885,15 @@ function Throw({error}) {
"react-dom": "canary",
"react-scripts": "^5.0.0",
"react-error-boundary": "4.0.3"
+=======
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
},
- "main": "/index.js"
-}
+});
```
-
+The onCaughtError option is a function called with two arguments:
+<<<<<<< HEAD
### Afficher un dialogue lors d'erreurs récupérables {/*displaying-a-dialog-for-recoverable-errors*/}
React est susceptible de refaire le rendu d'un composant afin de tenter de retomber sur ses pieds lorsqu'un rendu lève une erreur. S'il réussit, React affichera en console une erreur récupérable, pour notifier le développeur. Pour remplacer ce comportement, vous pouvez fournir l'option `onRecoverableError` :
@@ -1060,37 +1080,93 @@ export function reportUncaughtError({error, cause, componentStack}) {
export function reportRecoverableError({error, cause, componentStack}) {
reportError({ title: "Erreur récupérable", error, componentStack, dismissable: true });
+=======
+1. The error that was thrown.
+2. An errorInfo object that contains the componentStack of the error.
+
+Together with `onUncaughtError` and `onRecoverableError`, you can can implement your own error reporting system:
+
+
+
+```js src/reportError.js
+function reportError({ type, error, errorInfo }) {
+ // The specific implementation is up to you.
+ // `console.error()` is only used for demonstration purposes.
+ console.error(type, error, "Component Stack: ");
+ console.error("Component Stack: ", errorInfo.componentStack);
+}
+
+export function onCaughtErrorProd(error, errorInfo) {
+ if (error.message !== "Known error") {
+ reportError({ type: "Caught", error, errorInfo });
+ }
+}
+
+export function onUncaughtErrorProd(error, errorInfo) {
+ reportError({ type: "Uncaught", error, errorInfo });
+}
+
+export function onRecoverableErrorProd(error, errorInfo) {
+ reportError({ type: "Recoverable", error, errorInfo });
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
}
```
```js src/index.js active
import { createRoot } from "react-dom/client";
import App from "./App.js";
-import {reportRecoverableError} from "./reportError";
-import "./styles.css";
+import {
+ onCaughtErrorProd,
+ onRecoverableErrorProd,
+ onUncaughtErrorProd,
+} from "./reportError";
const container = document.getElementById("root");
const root = createRoot(container, {
- onRecoverableError: (error, errorInfo) => {
- reportRecoverableError({
- error,
- cause: error.cause,
- componentStack: errorInfo.componentStack,
- });
- }
+ // Keep in mind to remove these options in development to leverage
+ // React's default handlers or implement your own overlay for development.
+ // The handlers are only specfied unconditionally here for demonstration purposes.
+ onCaughtError: onCaughtErrorProd,
+ onRecoverableError: onRecoverableErrorProd,
+ onUncaughtError: onUncaughtErrorProd,
});
root.render();
```
```js src/App.js
-import { useState } from 'react';
-import { ErrorBoundary } from "react-error-boundary";
+import { Component, useState } from "react";
+
+function Boom() {
+ foo.bar = "baz";
+}
+
+class ErrorBoundary extends Component {
+ state = { hasError: false };
+ static getDerivedStateFromError(error) {
+ return { hasError: true };
+ }
+
+ render() {
+ if (this.state.hasError) {
+ return Something went wrong.
;
+ }
+ return this.props.children;
+ }
+}
+
+<<<<<<< HEAD
// 🚩 Bug : ne faites jamais ça. Ça va forcer une erreur.
let errorThrown = false;
+=======
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
export default function App() {
+ const [triggerUncaughtError, settriggerUncaughtError] = useState(false);
+ const [triggerCaughtError, setTriggerCaughtError] = useState(false);
+
return (
<>
+<<<<<<< HEAD
@@ -1128,12 +1204,33 @@ function Throw({error}) {
},
"main": "/index.js"
}
+=======
+
+ {triggerUncaughtError && }
+
+ {triggerCaughtError && (
+
+
+
+ )}
+ >
+ );
+}
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
```
+<<<<<<< HEAD
---
+=======
+## Troubleshooting {/*troubleshooting*/}
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
## Dépannage {/*troubleshooting*/}
diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md
index 92e6ec097..3676d61f2 100644
--- a/src/content/reference/react-dom/client/hydrateRoot.md
+++ b/src/content/reference/react-dom/client/hydrateRoot.md
@@ -41,10 +41,17 @@ React s'attachera au HTML existant à l'intérieur de `domNode`, et prendra la m
* `options` **optionnelles** : un objet avec des options pour la racine React.
+<<<<<<< HEAD
* `onCaughtError` **optionelle** : fonction de rappel appelée lorsque React capture une erreur au sein d'un Périmètre d'Erreur. Appelée avec l'`error` capturée par le Périmètre d'Erreur, et un objet `errorInfo` contenant la `componentStack`.
* `onUncaughtError` **optionnelle** : fonction de rappel appelée lorsqu'une erreur est levée sans être capturée par un Périmètre d'Erreur. Appelée avec l’`error` levée par React et un objet `errorInfo` contenant la `componentStack`.
* `onRecoverableError` **optionnel** : fonction de rappel appelée lorsque React retombe automatiquement sur ses pieds suite à une erreur. Appelée avec l’`error` levée par React et un objet `errorInfo` contenant la `componentStack`. Certaines de ces erreurs peuvent exposer leur cause originelle dans `error.cause`.
* `identifierPrefix` **optionnel** : un préfixe textuel utilisé pour les ID générés par [`useId`](/reference/react/useId). Pratique pour éviter les conflits entre les ID au sein de racines multiples sur une même page.
+=======
+ * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`.
+ * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`.
+ * **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with the `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`.
+ * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
#### Valeur renvoyée {/*returns*/}
@@ -97,7 +104,11 @@ Une appli entièrement construite avec React n'appellera généralement pas `roo
C'est principalement utile si le nœud DOM de votre racine React (ou un de ses ancêtres) est susceptible d'être retiré du DOM par du code tiers. Imaginez par exemple une gestion d'onglet basée sur jQuery qui retire les onglets inactifs du DOM. Si un onglet est retiré, tout ce qu'il contient (y compris d'éventuelles racines React) sera également retiré du DOM. Dans un tel cas, vous devez dire à React de « cesser » de gérer le contenu de la racine retirée en appelant `root.unmount`. Si vous ne le faisiez pas, les composants au sein de la racine retirée ne pourraient pas être nettoyés et libérer leurs ressources globales, telles que des abonnements.
+<<<<<<< HEAD
Un appel à `root.unmount` démontera tous les composants dans cette racine et « détachera » React du nœud DOM racine, y compris pour la gestion événementielle et les états de l'arbre.
+=======
+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.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
#### Paramètres {/*root-unmount-parameters*/}
@@ -267,7 +278,11 @@ export default function App() {
+<<<<<<< HEAD
Ça ne fonctionne qu'à un niveau de profondeur, et c'est vraiment une échappatoire. N'en abusez pas. React ne rattrapera le coup que pour les contenus textuels, il risque donc de rester quelques incohérences jusqu'au prochain rendu.
+=======
+This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. React will **not** attempt to patch mismatched text content.
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
---
@@ -371,10 +386,15 @@ export default function App({counter}) {
Il est toutefois rare d'appeler [`root.render`](#root-render) sur une racine hydratée. En général, vos composants [mettront plutôt à jour l'état](/reference/react/useState).
+<<<<<<< HEAD
### Afficher un dialogue lors d'erreurs non capturées {/*show-a-dialog-for-uncaught-errors*/}
+=======
+### Error logging in production {/*error-logging-in-production*/}
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
-
+By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`:
+<<<<<<< HEAD
`onUncaughtError` n'est disponible que dans la dernière version React Canary.
@@ -567,21 +587,22 @@ export function reportRecoverableError({error, cause, componentStack}) {
```
```js src/index.js active
+=======
+```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]]
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
import { hydrateRoot } from "react-dom/client";
-import App from "./App.js";
-import {reportUncaughtError} from "./reportError";
-import "./styles.css";
-import {renderToString} from 'react-dom/server';
+import { reportCaughtError } from "./reportError";
const container = document.getElementById("root");
-const root = hydrateRoot(container, , {
- onUncaughtError: (error, errorInfo) => {
- if (error.message !== 'Known error') {
- reportUncaughtError({
+const root = hydrateRoot(container, {
+ onCaughtError: (error, errorInfo) => {
+ if (error.message !== "Known error") {
+ reportCaughtError({
error,
- componentStack: errorInfo.componentStack
+ componentStack: errorInfo.componentStack,
});
}
+<<<<<<< HEAD
}
});
```
@@ -648,10 +669,15 @@ const root = hydrateRoot(
}
);
root.render();
+=======
+ },
+});
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
```
L'option onCaughtError est une fonction avec deux arguments :
+<<<<<<< HEAD
1. L'error qui a été capturée par le Périmètre.
2. Un objet errorInfo qui contient la componentStack de l'erreur.
@@ -813,45 +839,87 @@ export function reportUncaughtError({error, cause, componentStack}) {
export function reportRecoverableError({error, cause, componentStack}) {
reportError({ title: "Erreur récupérable", error, componentStack, dismissable: true });
+=======
+1. The error that was thrown.
+2. An errorInfo object that contains the componentStack of the error.
+
+Together with `onUncaughtError` and `onRecoverableError`, you can implement your own error reporting system:
+
+
+
+```js src/reportError.js
+function reportError({ type, error, errorInfo }) {
+ // The specific implementation is up to you.
+ // `console.error()` is only used for demonstration purposes.
+ console.error(type, error, "Component Stack: ");
+ console.error("Component Stack: ", errorInfo.componentStack);
+}
+
+export function onCaughtErrorProd(error, errorInfo) {
+ if (error.message !== "Known error") {
+ reportError({ type: "Caught", error, errorInfo });
+ }
+}
+
+export function onUncaughtErrorProd(error, errorInfo) {
+ reportError({ type: "Uncaught", error, errorInfo });
+}
+
+export function onRecoverableErrorProd(error, errorInfo) {
+ reportError({ type: "Recoverable", error, errorInfo });
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
}
```
```js src/index.js active
import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
-import {reportCaughtError} from "./reportError";
-import "./styles.css";
+import {
+ onCaughtErrorProd,
+ onRecoverableErrorProd,
+ onUncaughtErrorProd,
+} from "./reportError";
const container = document.getElementById("root");
-const root = hydrateRoot(container, , {
- onCaughtError: (error, errorInfo) => {
- if (error.message !== 'Known error') {
- reportCaughtError({
- error,
- componentStack: errorInfo.componentStack
- });
- }
- }
+hydrateRoot(container, , {
+ // Keep in mind to remove these options in development to leverage
+ // React's default handlers or implement your own overlay for development.
+ // The handlers are only specfied unconditionally here for demonstration purposes.
+ onCaughtError: onCaughtErrorProd,
+ onRecoverableError: onRecoverableErrorProd,
+ onUncaughtError: onUncaughtErrorProd,
});
```
```js src/App.js
-import { useState } from 'react';
-import { ErrorBoundary } from "react-error-boundary";
+import { Component, useState } from "react";
-export default function App() {
- const [error, setError] = useState(null);
-
- function handleUnknown() {
- setError("unknown");
+function Boom() {
+ foo.bar = "baz";
+}
+
+class ErrorBoundary extends Component {
+ state = { hasError: false };
+
+ static getDerivedStateFromError(error) {
+ return { hasError: true };
}
- function handleKnown() {
- setError("known");
+ render() {
+ if (this.state.hasError) {
+ return Something went wrong.
;
+ }
+ return this.props.children;
}
-
+}
+
+export default function App() {
+ const [triggerUncaughtError, settriggerUncaughtError] = useState(false);
+ const [triggerCaughtError, setTriggerCaughtError] = useState(false);
+
return (
<>
+<<<<<<< HEAD
{
@@ -939,6 +1007,26 @@ Vous pouvez utiliser l'option `onRecoverableError` pour afficher des dialogues d
```html index.html hidden
+=======
+
+ {triggerUncaughtError && }
+
+ {triggerCaughtError && (
+
+
+
+ )}
+ >
+ );
+}
+```
+
+```html public/index.html hidden
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
@@ -946,6 +1034,7 @@ Vous pouvez utiliser l'option `onRecoverableError` pour afficher des dialogues d
@@ -1161,6 +1250,14 @@ function Throw({error}) {
}
```
+=======
+ Purposefully using HTML content that differs from the server-rendered content to trigger recoverable errors.
+-->
+Server content before hydration.
+
+
+```
+>>>>>>> ab18d2f0f5151ab0c927a12eb0a64f8170762eff
## Dépannage {/*troubleshooting*/}
diff --git a/src/content/reference/react-dom/components/common.md b/src/content/reference/react-dom/components/common.md
index b689fc043..79401f19f 100644
--- a/src/content/reference/react-dom/components/common.md
+++ b/src/content/reference/react-dom/components/common.md
@@ -246,6 +246,7 @@ Ces événements sont déclenchés pour les ressources comme [`