Skip to content
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
17 changes: 14 additions & 3 deletions src/content/5/en/part5b.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,15 @@ We can add any React elements we want between the opening and closing tags of <i

The code for the <i>Togglable</i> component is shown below:

Motivation: Currently, the material explains how to use useImperativeHandle but misses the crucial step of wrapping
the component in forwardRef. In modern React, failing to do so results in a TypeError: Cannot read properties of undefined (reading 'toggleVisibility').

Changes: Added a code example about forwardRef to ensure students don't encounter this crash when following the tutorial.

```js
import { useState } from 'react'
import { useState, useImperativeHandle, forwardRef } from 'react'

const Togglable = (props) => {
const Togglable = forwardRef((props, ref) => {
const [visible, setVisible] = useState(false)

const hideWhenVisible = { display: visible ? 'none' : '' }
Expand All @@ -198,6 +203,12 @@ const Togglable = (props) => {
setVisible(!visible)
}

useImperativeHandle(ref, () => {
return {
toggleVisibility
}
})

return (
<div>
<div style={hideWhenVisible}>
Expand All @@ -209,7 +220,7 @@ const Togglable = (props) => {
</div>
</div>
)
}
})

export default Togglable
```
Expand Down