I have the following in a react native application:
export default function MyScreen() {
const componentRefs = useRef([]);
return (
<View >
{myArray.map(
(wc, index) =>
(
<MyObject
key={index}
ref={el => componentRefs.current[index] = el}
index={index}
// other props
/>
)
)}
</View>
);
}
Each MyObject
instance displays a word. I want to add functionality which will, when a button is pressed, highlight each word in turn, and play an audio file with its pronunciation.
In order to do this, I need to store reference to each MyObject
instance in the parent MyScreen
function, so I can subsequently traverse through all the displayed words.
My initial stab at this is to use useRef
to create an array to store the references, as illustrated above.
As an initial test, I have a button handler to check if the references have been saved. This simply loops through each item in componentRefs
:
componentRefs.current.forEach((x) => console.log(x));
However, nothing is displayed.
There is also a warning:
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
What is the best way to store the references in the parent to enable the desired functionality?
Thanks very much
2
Answers
Please try with below Code:
Use this code example to use
useRef
inside loop. This is just an example, change components according to you.