diff --git a/src/content/5/en/part5b.md b/src/content/5/en/part5b.md index d13f2b9bfc9..1d4756a7b00 100644 --- a/src/content/5/en/part5b.md +++ b/src/content/5/en/part5b.md @@ -185,10 +185,15 @@ We can add any React elements we want between the opening and closing tags of Togglable 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' : '' } @@ -198,6 +203,12 @@ const Togglable = (props) => { setVisible(!visible) } + useImperativeHandle(ref, () => { + return { + toggleVisibility + } + }) + return (