Skip to content

Update part5b.md forwardRef #4034

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: source
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/content/5/en/part5b.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,9 +388,9 @@ The [useRef](https://react.dev/reference/react/useRef) hook is used to create a
We also make the following changes to the <i>Togglable</i> component:

```js
import { useState, forwardRef, useImperativeHandle } from 'react' // highlight-line
import { useState, useImperativeHandle } from 'react' // highlight-line

const Togglable = forwardRef((props, refs) => { // highlight-line
const Togglable = (props) => { // highlight-line
const [visible, setVisible] = useState(false)

const hideWhenVisible = { display: visible ? 'none' : '' }
Expand All @@ -401,7 +401,7 @@ const Togglable = forwardRef((props, refs) => { // highlight-line
}

// highlight-start
useImperativeHandle(refs, () => {
useImperativeHandle(props.ref, () => {
return {
toggleVisibility
}
Expand All @@ -419,12 +419,14 @@ const Togglable = forwardRef((props, refs) => { // highlight-line
</div>
</div>
)
}) // highlight-line
} // highlight-line

export default Togglable
```

The function that creates the component is wrapped inside of a [forwardRef](https://react.dev/reference/react/forwardRef) function call. This way the component can access the ref that is assigned to it.
The reference assigned to the component can be accessed as a prop using `props.ref`.

**NOTE:** Before React 19 the function that creates the component was supposed to be wrapped inside of a [forwardRef](https://react.dev/reference/react/forwardRef) function call to enable the component to access the ref assigned to it, that is no longer required, as it's now possible to access the ref as a prop.

The component uses the [useImperativeHandle](https://react.dev/reference/react/useImperativeHandle) hook to make its <i>toggleVisibility</i> function available outside of the component.

Expand Down