diff --git a/src/content/reference/react/forwardRef.md b/src/content/reference/react/forwardRef.md index 739c94ae2..bf9a2f9e3 100644 --- a/src/content/reference/react/forwardRef.md +++ b/src/content/reference/react/forwardRef.md @@ -4,7 +4,7 @@ title: forwardRef -`forwardRef` lets your component expose a DOM node to parent component with a [ref.](/learn/manipulating-the-dom-with-refs) +`forwardRef` дозволяє вашому компоненту розкрити DOM-вузол батьківському компоненту через [реф.](/learn/manipulating-the-dom-with-refs) ```js const SomeComponent = forwardRef(render) @@ -16,11 +16,11 @@ const SomeComponent = forwardRef(render) --- -## Reference {/*reference*/} +## Опис {/*reference*/} ### `forwardRef(render)` {/*forwardref*/} -Call `forwardRef()` to let your component receive a ref and forward it to a child component: +Викличте `forwardRef()`, щоб ваш компонент зміг отримати реф та направити його до дочірнього компонента: ```js import { forwardRef } from 'react'; @@ -30,26 +30,25 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -[See more examples below.](#usage) +[Перегляньте більше прикладів нижче.](#usage) -#### Parameters {/*parameters*/} +#### Параметри {/*parameters*/} -* `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. +* `render`: Функція для рендеру вашого компонента. React викликає цю функцію з пропсами і `ref`, які ваш компонент отримав від батьківського компонента. JSX, який ви повертаєте, буде виводом вашого компонента. -#### Returns {/*returns*/} +#### Результат {/*returns*/} -`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. +`forwardRef` повертає React-компонент, який можна рендерити в JSX. На відміну від React-компонентів, створених звичайними функціями, компонент повернутий з `forwardRef` також може отримувати `ref` проп. -#### Caveats {/*caveats*/} - -* 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. +#### Застереження {/*caveats*/} +* У строгому режимі React **викличе вашу функцію для рендеру двічі**, щоб [допомогти вам знаходити побічні ефекти.](#my-initializer-or-updater-function-runs-twice) Ця поведінка діє лише під час розробки і не впливає на продакшн. Якщо ваша функція для рендеру є чистою (якою вона й повинна бути), то ця поведінка не вплине на логіку вашого компонента. Результат одного з викликів буде проігноровано. --- -### `render` function {/*render-function*/} +### Функція `render` {/*render-function*/} -`forwardRef` accepts a render function as an argument. React calls this function with `props` and `ref`: +`forwardRef` приймає функцію для рендеру як аргумент. React викликає цю функцію з `props` та `ref`: ```js const MyInput = forwardRef(function MyInput(props, ref) { @@ -62,23 +61,23 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -#### Parameters {/*render-parameters*/} +#### Параметри {/*render-parameters*/} -* `props`: The props passed by the parent component. +* `props`: Пропси передані батьківським компонентом. -* `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) +* `ref`: Атрибут `ref`, переданий батьківським компонентом. `ref` може бути об'єктом чи функцією. Якщо батьківський компонент не передав реф, то цей параметр буде `null`. Вам потрібно або передати отриманий `ref` до іншого компонента, або передати його в [`useImperativeHandle`.](/reference/react/useImperativeHandle) -#### Returns {/*render-returns*/} +#### Результат {/*render-returns*/} -`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. +`forwardRef` повертає React-компонент, який можна рендерити в JSX. На відміну від React-компонентів, створених звичайними функціями, компонент повернутий з `forwardRef` також може отримувати `ref` проп. --- -## Usage {/*usage*/} +## Використання {/*usage*/} -### Exposing a DOM node to the parent component {/*exposing-a-dom-node-to-the-parent-component*/} +### Розкриття DOM-вузла батьківському компоненту {/*exposing-a-dom-node-to-the-parent-component*/} -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()`: +За замовчуванням, DOM-вузли кожного компонента приватні. Але, іноді потрібно передавати DOM-вузол батьківському компоненту, наприклад, щоб мати можливість сфокусувати його. Щоб зробити це, обгорніть оголошення вашого компонента в `forwardRef()`: ```js {3,11} import { forwardRef } from 'react'; @@ -94,7 +93,7 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -You will receive a ref as the second argument after props. Pass it to the DOM node that you want to expose: +Ви отримаєте реф як другий аргумент після пропсів. Передайте його у DOM-вузол, який хочете розкрити: ```js {8} [[1, 3, "ref"], [1, 8, "ref", 30]] import { forwardRef } from 'react'; @@ -110,7 +109,7 @@ const MyInput = forwardRef(function MyInput(props, ref) { }); ``` -This lets the parent `Form` component access the `` DOM node exposed by `MyInput`: +Це дозволяє батьківському компоненту `Form` отримати доступ до `` DOM-вузла, розкритого в `MyInput`: ```js [[1, 2, "ref"], [1, 10, "ref", 41], [2, 5, "ref.current"]] function Form() { @@ -124,22 +123,22 @@ function Form() {
); } ``` -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 `` browser tag. As a result, the `Form` component can access that `` DOM node and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it. +Цей компонент `Form` [передає реф](/reference/react/useRef#manipulating-the-dom-with-a-ref) до `MyInput`. Компонент `MyInput` *направляє* той реф до браузерного тегу ``. Як результат, компонент `Form` має доступ до DOM-вузла `` та може викликати [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) на ньому. -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. +Пам'ятайте, що розкриття рефу DOM-вузла всередині вашого компонента робить важчою зміну внутрішніх частин компонента пізніше. Зазвичай, ви будете розкривати DOM-вузли з компонентів нижнього рівня, що перевикористовуються (як-от кнопки та поля вводу), та не будете робити це із глобальними компонентами, такими як аватар чи коментар. - + -#### Focusing a text input {/*focusing-a-text-input*/} +#### Фокусування на текстовому полі {/*focusing-a-text-input*/} -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 ``. This lets the `Form` component focus the ``. +Натискання кнопки сфокусує курсор на полі вводу. Компонент `Form` оголошує реф і передає його до компонента `MyInput`. Компонент `MyInput` направляє той реф до браузерного ``. Це дозволяє компоненту `Form` сфокусувати курсор на ``. @@ -158,7 +157,7 @@ export default function Form() {
); @@ -191,9 +190,9 @@ input { -#### Playing and pausing a video {/*playing-and-pausing-a-video*/} +#### Відтворення та зупинка відео {/*playing-and-pausing-a-video*/} -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 `