Skip to content

Commit efe3d4c

Browse files
authored
Merge pull request #512 from reactjs/copy/forwardref
Translation of the "forwardRef" page
2 parents a8b59bc + f7acf5d commit efe3d4c

File tree

1 file changed

+64
-62
lines changed

1 file changed

+64
-62
lines changed

src/content/reference/react/forwardRef.md

Lines changed: 64 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ title: forwardRef
44

55
<Intro>
66

7-
`forwardRef` lets your component expose a DOM node to parent component with a [ref.](/learn/manipulating-the-dom-with-refs)
7+
`forwardRef` permet à votre composant d'exposer un nœud DOM à son composant parent au travers d'une [ref](/learn/manipulating-the-dom-with-refs).
8+
89

910
```js
1011
const SomeComponent = forwardRef(render)
@@ -16,11 +17,11 @@ const SomeComponent = forwardRef(render)
1617

1718
---
1819

19-
## Reference {/*reference*/}
20+
## Référence {/*reference*/}
2021

2122
### `forwardRef(render)` {/*forwardref*/}
2223

23-
Call `forwardRef()` to let your component receive a ref and forward it to a child component:
24+
Appelez `forwardRef()` pour que votre composant reçoive une ref qu'il puisse transmette à un de ses composants enfants :
2425

2526
```js
2627
import { forwardRef } from 'react';
@@ -30,26 +31,25 @@ const MyInput = forwardRef(function MyInput(props, ref) {
3031
});
3132
```
3233

33-
[See more examples below.](#usage)
34-
35-
#### Parameters {/*parameters*/}
34+
[Voir dautres exemples ci-dessous](#usage).
3635

37-
* `render`: The render function for your component. React calls this function with the props and `ref` that your component received from its parent. The JSX you return will be the output of your component.
36+
#### Paramètres {/*parameters*/}
3837

39-
#### Returns {/*returns*/}
38+
* `render` : la fonction de rendu de votre composant. React appellera cette fonction avec les props et la `ref` que votre composant aura reçu de son parent. Cette fonction renvoie, comme d'habitude, le JSX constitutif du composant.
4039

41-
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by `forwardRef` is also able to receive a `ref` prop.
40+
#### Valeur renvoyée {/*returns*/}
4241

43-
#### Caveats {/*caveats*/}
42+
`forwardRef` renvoie un composant React qui peut figurer dans un rendu JSX. Contrairement aux composants React définis par des fonctions classiques, un composant renvoyé par `forwardRef` pourra en prime accepter une prop `ref`.
4443

45-
* In Strict Mode, React will **call your render function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your render function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
44+
#### Limitations {/*caveats*/}
4645

46+
* En mode strict, React **appellera votre fonction composant deux fois** afin de [vous aider à repérer des impuretés accidentelles](#my-initializer-or-updater-function-runs-twice). Ce comportement est limité au développement et n'affecte pas la production. Une des valeurs renvoyées sera ignorée. Si votre fonction composant est pure (ce qui devrait être le cas), ça n'affectera en rien son comportement.
4747

4848
---
4949

50-
### `render` function {/*render-function*/}
50+
### La fonction `render` {/*render-function*/}
5151

52-
`forwardRef` accepts a render function as an argument. React calls this function with `props` and `ref`:
52+
`forwardRef` accepte une fonction de rendu en argument. React appellera cette fonction avec `props` et `ref` :
5353

5454
```js
5555
const MyInput = forwardRef(function MyInput(props, ref) {
@@ -62,23 +62,23 @@ const MyInput = forwardRef(function MyInput(props, ref) {
6262
});
6363
```
6464

65-
#### Parameters {/*render-parameters*/}
65+
#### Paramètres {/*render-parameters*/}
6666

67-
* `props`: The props passed by the parent component.
67+
* `props` : les props passées par le composant parent.
6868

69-
* `ref`: The `ref` attribute passed by the parent component. The `ref` can be an object or a function. If the parent component has not passed a ref, it will be `null`. You should either pass the `ref` you receive to another component, or pass it to [`useImperativeHandle`.](/reference/react/useImperativeHandle)
69+
* `ref` : la prop `ref` passée par le composant parent. La `ref` peut être un objet ou une fonction. Si le composant parent n'a pas passé de ref, elle sera `null`. Vous pouvez soit passer la `ref` reçue à un autre composant soit la passer à [`useImperativeHandle`](/reference/react/useImperativeHandle).
7070

71-
#### Returns {/*render-returns*/}
71+
#### Valeur renvoyée {/*render-returns*/}
7272

73-
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by `forwardRef` is able to take a `ref` prop.
73+
`forwardRef` renvoie un composant React qui peut figurer dans un rendu JSX. Contrairement aux composants React définis par des fonctions classiques, un composant renvoyé par `forwardRef` pourra en prime accepter une prop `ref`.
7474

7575
---
7676

77-
## Usage {/*usage*/}
77+
## Utilisation {/*usage*/}
7878

79-
### Exposing a DOM node to the parent component {/*exposing-a-dom-node-to-the-parent-component*/}
79+
### Exposer un nœud DOM au composant parent {/*exposing-a-dom-node-to-the-parent-component*/}
8080

81-
By default, each component's DOM nodes are private. However, sometimes it's useful to expose a DOM node to the parent--for example, to allow focusing it. To opt in, wrap your component definition into `forwardRef()`:
81+
Par défaut, tous les nœuds DOM de votre composant sont privés. Ceci dit, il peut parfois être utile d'exposer un nœud DOM à votre parent — par exemple pour en permettre l'activation. Pour permettre ça, enrobez votre définition de composant avec `forwardRef()` :
8282

8383
```js {3,11}
8484
import { forwardRef } from 'react';
@@ -94,7 +94,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
9494
});
9595
```
9696

97-
You will receive a <CodeStep step={1}>ref</CodeStep> as the second argument after props. Pass it to the DOM node that you want to expose:
97+
Vous recevrez une <CodeStep step={1}>ref</CodeStep> comme second argument, juste après les props. Passez-la au nœud DOM que vous souhaitez exposer :
9898

9999
```js {8} [[1, 3, "ref"], [1, 8, "ref", 30]]
100100
import { forwardRef } from 'react';
@@ -110,7 +110,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
110110
});
111111
```
112112

113-
This lets the parent `Form` component access the <CodeStep step={2}>`<input>` DOM node</CodeStep> exposed by `MyInput`:
113+
Ça permet au composant parent `Form` d'accéder au <CodeStep step={2}>nœud DOM `<input>`</CodeStep> exposé par `MyInput` :
114114

115115
```js [[1, 2, "ref"], [1, 10, "ref", 41], [2, 5, "ref.current"]]
116116
function Form() {
@@ -122,24 +122,24 @@ function Form() {
122122

123123
return (
124124
<form>
125-
<MyInput label="Enter your name:" ref={ref} />
125+
<MyInput label="Saisissez votre nom :" ref={ref} />
126126
<button type="button" onClick={handleClick}>
127-
Edit
127+
Modifier
128128
</button>
129129
</form>
130130
);
131131
}
132132
```
133133

134-
This `Form` component [passes a ref](/reference/react/useRef#manipulating-the-dom-with-a-ref) to `MyInput`. The `MyInput` component *forwards* that ref to the `<input>` browser tag. As a result, the `Form` component can access that `<input>` DOM node and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it.
134+
Le composant `Form` [passe une ref](/reference/react/useRef#manipulating-the-dom-with-a-ref) à `MyInput`. Le composant `MyInput` *transmet* cette ref à la balise native `<input>`. Résultat, le composant `Form` peut accéder au nœud DOM `<input>` et appeler sa méthode [`focus()`](https://developer.mozilla.org/fr/docs/Web/API/HTMLElement/focus).
135135

136-
Keep in mind that exposing a ref to the DOM node inside your component makes it harder to change your component's internals later. You will typically expose DOM nodes from reusable low-level components like buttons or text inputs, but you won't do it for application-level components like an avatar or a comment.
136+
Gardez à l'esprit qu'exposer une ref vers un nœud DOM au sein de votre composant peut vous embêter plus tard si vous souhaitez refondre la structure interne de celui-ci. Classiquement, vous exposerez des nœuds DOM depuis des composants réutilisables de bas niveau tels que des boutons ou des champs de saisie, mais vous éviterez de le faire pour des composants applicatifs comme un avatar ou un bloc de commentaire.
137137

138-
<Recipes title="Examples of forwarding a ref">
138+
<Recipes title="Exemples de transmission de ref">
139139

140-
#### Focusing a text input {/*focusing-a-text-input*/}
140+
#### Activer un champ de saisie {/*focusing-a-text-input*/}
141141

142-
Clicking the button will focus the input. The `Form` component defines a ref and passes it to the `MyInput` component. The `MyInput` component forwards that ref to the browser `<input>`. This lets the `Form` component focus the `<input>`.
142+
Un clic sur le bouton activera le champ de saisie. Le composant `Form` définit une ref qu'il passe au composant `MyInput`. Ce composant `MyInput` transmet la ref au `<input>` du navigateur. Ça permet au composant `Form` d'activer le `<input>`.
143143

144144
<Sandpack>
145145

@@ -156,9 +156,9 @@ export default function Form() {
156156

157157
return (
158158
<form>
159-
<MyInput label="Enter your name:" ref={ref} />
159+
<MyInput label="Saisissez votre nom :" ref={ref} />
160160
<button type="button" onClick={handleClick}>
161-
Edit
161+
Modifier
162162
</button>
163163
</form>
164164
);
@@ -191,9 +191,9 @@ input {
191191

192192
<Solution />
193193

194-
#### Playing and pausing a video {/*playing-and-pausing-a-video*/}
194+
#### Lire et mettre en pause une vidéo {/*playing-and-pausing-a-video*/}
195195

196-
Clicking the button will call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on a `<video>` DOM node. The `App` component defines a ref and passes it to the `MyVideoPlayer` component. The `MyVideoPlayer` component forwards that ref to the browser `<video>` node. This lets the `App` component play and pause the `<video>`.
196+
Ici un clic sur le bouton appellera les méthodes [`play()`](https://developer.mozilla.org/fr/docs/Web/API/HTMLMediaElement/play) et [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) d'un nœud DOM `<video>`. Le composant `App` définit une ref qu'il passe au composant `MyVideoPlayer`. Ce composant `MyVideoPlayer` transmet cette ref au nœud `<video>` du navigateur. Ça permet au composant `App` de lire et mettre en pause la `<video>`.
197197

198198
<Sandpack>
199199

@@ -206,7 +206,7 @@ export default function App() {
206206
return (
207207
<>
208208
<button onClick={() => ref.current.play()}>
209-
Play
209+
Lecture
210210
</button>
211211
<button onClick={() => ref.current.pause()}>
212212
Pause
@@ -252,9 +252,9 @@ button { margin-bottom: 10px; margin-right: 10px; }
252252

253253
---
254254

255-
### Forwarding a ref through multiple components {/*forwarding-a-ref-through-multiple-components*/}
255+
### Transmettre une ref à travers plusieurs composants {/*forwarding-a-ref-through-multiple-components*/}
256256

257-
Instead of forwarding a `ref` to a DOM node, you can forward it to your own component like `MyInput`:
257+
Au lieu de transmettre la `ref` à un nœud DOM, vous avez parfois besoin de la transmettre à votre propre composant, comme `MyInput` :
258258

259259
```js {1,5}
260260
const FormField = forwardRef(function FormField(props, ref) {
@@ -268,7 +268,7 @@ const FormField = forwardRef(function FormField(props, ref) {
268268
});
269269
```
270270

271-
If that `MyInput` component forwards a ref to its `<input>`, a ref to `FormField` will give you that `<input>`:
271+
Si ce composant `MyInput` transmet une ref à son `<input>`, une ref à `FormField` vous donnera ce `<input>` :
272272

273273
```js {2,5,10}
274274
function Form() {
@@ -280,16 +280,16 @@ function Form() {
280280

281281
return (
282282
<form>
283-
<FormField label="Enter your name:" ref={ref} isRequired={true} />
283+
<FormField label="Saisissez votre nom :" ref={ref} isRequired={true} />
284284
<button type="button" onClick={handleClick}>
285-
Edit
285+
Modifier
286286
</button>
287287
</form>
288288
);
289289
}
290290
```
291291

292-
The `Form` component defines a ref and passes it to `FormField`. The `FormField` component forwards that ref to `MyInput`, which forwards it to a browser `<input>` DOM node. This is how `Form` accesses that DOM node.
292+
Le composant `Form` définit une ref et la passer au `FormField `. Le composant `FormField` transmet cette ref au `MyInput`, qui la transmet au nœud DOM `<input>`. C'est ainsi que `Form` accède à ce nœud DOM.
293293

294294

295295
<Sandpack>
@@ -307,9 +307,9 @@ export default function Form() {
307307

308308
return (
309309
<form>
310-
<FormField label="Enter your name:" ref={ref} isRequired={true} />
310+
<FormField label="Saisissez votre nom :" ref={ref} isRequired={true} />
311311
<button type="button" onClick={handleClick}>
312-
Edit
312+
Modifier
313313
</button>
314314
</form>
315315
);
@@ -328,10 +328,10 @@ const FormField = forwardRef(function FormField({ label, isRequired }, ref) {
328328
ref={ref}
329329
label={label}
330330
value={value}
331-
onChange={e => setValue(e.target.value)}
331+
onChange={e => setValue(e.target.value)}
332332
/>
333333
{(isRequired && value === '') &&
334-
<i>Required</i>
334+
<i>Requis</i>
335335
}
336336
</>
337337
);
@@ -367,9 +367,9 @@ input, button {
367367

368368
---
369369

370-
### Exposing an imperative handle instead of a DOM node {/*exposing-an-imperative-handle-instead-of-a-dom-node*/}
370+
### Exposer un point d'accès impératif plutôt qu'un nœud DOM {/*exposing-an-imperative-handle-instead-of-a-dom-node*/}
371371

372-
Instead of exposing an entire DOM node, you can expose a custom object, called an *imperative handle,* with a more constrained set of methods. To do this, you'd need to define a separate ref to hold the DOM node:
372+
Au lieu d'exposer l'intégralité du nœud DOM, vous pouvez exposer un objet personnalisé qu'on appelle *point d'accès impératif*, doté d'un jeu plus restreint de méthodes. Pour cela, vous devez définir une ref séparée pour référencer le nœud DOM :
373373

374374
```js {2,6}
375375
const MyInput = forwardRef(function MyInput(props, ref) {
@@ -381,7 +381,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
381381
});
382382
```
383383

384-
Pass the `ref` you received to [`useImperativeHandle`](/reference/react/useImperativeHandle) and specify the value you want to expose to the `ref`:
384+
Passez la `ref` que vous avez reçue à [`useImperativeHandle`](/reference/react/useImperativeHandle) et spécifiez la valeur que vous souhaitez exposer en tant que `ref` :
385385

386386
```js {6-15}
387387
import { forwardRef, useRef, useImperativeHandle } from 'react';
@@ -404,7 +404,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
404404
});
405405
```
406406

407-
If some component gets a ref to `MyInput`, it will only receive your `{ focus, scrollIntoView }` object instead of the DOM node. This lets you limit the information you expose about your DOM node to the minimum.
407+
Si un composant récupère la ref de `MyInput`, il ne recevra que votre objet `{ focus, scrollIntoView }` au lieu du nœud DOM. Ça vous permet de limiter au minimum les parties du nœud DOM que vous exposez.
408408

409409
<Sandpack>
410410

@@ -417,15 +417,16 @@ export default function Form() {
417417

418418
function handleClick() {
419419
ref.current.focus();
420-
// This won't work because the DOM node isn't exposed:
420+
// Ça ne marchera pas parce que le nœud DOM
421+
// n'est pas exposé :
421422
// ref.current.style.opacity = 0.5;
422423
}
423424

424425
return (
425426
<form>
426-
<MyInput label="Enter your name:" ref={ref} />
427+
<MyInput label="Saisissez votre nom :" ref={ref} />
427428
<button type="button" onClick={handleClick}>
428-
Edit
429+
Modifier
429430
</button>
430431
</form>
431432
);
@@ -463,25 +464,26 @@ input {
463464

464465
</Sandpack>
465466

466-
[Read more about using imperative handles.](/reference/react/useImperativeHandle)
467+
[En savoir plus sur les points d'accès impératifs](/reference/react/useImperativeHandle).
467468

468469
<Pitfall>
469470

470-
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can't express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
471471

472-
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
472+
**N'abusez pas des refs.** Vous ne devriez utiliser des refs que pour des comportements *impératifs* qui ne peuvent pas être exprimés par des props : faire défiler jusqu'à un nœud, activer un nœud, déclencher une animation, sélectionner un texte, et ainsi de suite.
473+
474+
**Si vous pouvez exprimer quelque chose sous forme de prop, n'utilisez pas une ref.** Par exemple, plutôt que d'exposer un objet impératif du genre `{ open, close }` depuis un composant `Modal`, préférez proposer une prop `isOpen` pour une utilisation du style `<Modal isOpen={isOpen} />`. [Les Effets](/learn/synchronizing-with-effects) peuvent vous aider à exposer des comportements impératifs au travers de props.
473475

474476
</Pitfall>
475477

476478
---
477479

478-
## Troubleshooting {/*troubleshooting*/}
480+
## Dépannage {/*troubleshooting*/}
479481

480-
### My component is wrapped in `forwardRef`, but the `ref` to it is always `null` {/*my-component-is-wrapped-in-forwardref-but-the-ref-to-it-is-always-null*/}
482+
### Mon composant est enrobé par `forwardRef`, mais la `ref` que je reçois est toujours `null` {/*my-component-is-wrapped-in-forwardref-but-the-ref-to-it-is-always-null*/}
481483

482-
This usually means that you forgot to actually use the `ref` that you received.
484+
Ça signifie généralement que vous avez oublié d'utiliser effectivement la ref que vous avez reçue.
483485

484-
For example, this component doesn't do anything with its `ref`:
486+
Par exemple, ce composant ne fait rien avec sa `ref` :
485487

486488
```js {1}
487489
const MyInput = forwardRef(function MyInput({ label }, ref) {
@@ -494,7 +496,7 @@ const MyInput = forwardRef(function MyInput({ label }, ref) {
494496
});
495497
```
496498

497-
To fix it, pass the `ref` down to a DOM node or another component that can accept a ref:
499+
Pour corriger ça, transmettez la `ref` au nœud DOM ou à un autre composant qui peut acccepter une ref :
498500

499501
```js {1,5}
500502
const MyInput = forwardRef(function MyInput({ label }, ref) {
@@ -507,7 +509,7 @@ const MyInput = forwardRef(function MyInput({ label }, ref) {
507509
});
508510
```
509511

510-
The `ref` to `MyInput` could also be `null` if some of the logic is conditional:
512+
La `ref` à `MyInput` pourrait aussi être `null` si une partie de la logique était conditionnelle :
511513

512514
```js {1,5}
513515
const MyInput = forwardRef(function MyInput({ label, showInput }, ref) {
@@ -520,7 +522,7 @@ const MyInput = forwardRef(function MyInput({ label, showInput }, ref) {
520522
});
521523
```
522524

523-
If `showInput` is `false`, then the ref won't be forwarded to any node, and a ref to `MyInput` will remain empty. This is particularly easy to miss if the condition is hidden inside another component, like `Panel` in this example:
525+
Si `showInput` est `false`, alors la ref ne sera transmise à aucun nœud, et la ref à `MyInput` restera vide. C'est particulièrement difficile à repérer si la condition est enfouie dans un autre composant, comme `Panel` dans l'exemple ci-après :
524526

525527
```js {5,7}
526528
const MyInput = forwardRef(function MyInput({ label, showInput }, ref) {

0 commit comments

Comments
 (0)