When I write this code I have an error:
React Hook "useRef" cannot be called inside a callback. React Hooks must be called in a React function ponent or a custom React Hook function
What should I do with this code?
return ITEMS.map((item, i) => {
const elementRef = useRef(null);
return (
<div
ref={elementRef}
key={i}
>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item
parentRef={elementRef}
/>
)}
</Wrapper>
</div>
);
}
When I write this code I have an error:
React Hook "useRef" cannot be called inside a callback. React Hooks must be called in a React function ponent or a custom React Hook function
What should I do with this code?
return ITEMS.map((item, i) => {
const elementRef = useRef(null);
return (
<div
ref={elementRef}
key={i}
>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item
parentRef={elementRef}
/>
)}
</Wrapper>
</div>
);
}
Share
Improve this question
edited Apr 28, 2020 at 21:29
halfer
20.3k19 gold badges109 silver badges202 bronze badges
asked Apr 28, 2020 at 20:56
aaaaniaaaaania
931 gold badge1 silver badge5 bronze badges
2
-
Use
createRef
instead? – Yevhen Horbunkov Commented Apr 28, 2020 at 21:17 - Does this answer your question? How can I use multiple refs for an array of elements with hooks? – user120242 Commented Apr 28, 2020 at 21:26
1 Answer
Reset to default 4Here are two possibilities, Either using useRef
with an object/array, or using createRef
as suggested by Yevgen Gorbunkov.
I'm not entirely sure as to the viability of these as the createRef
option will create entirely new refs on each render, and the useRef
option you'll need to make sure your keys/indexes are always the same.
const ITEMS = [{ name: "test" }, { name: "test2" }];
export default function App() {
const ref = useRef({});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{ITEMS.map((item, idx) => {
return (
<div key={idx} ref={element => (ref.current[idx] = element)}>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item parentRef={ref.current[idx]} />
)}
</Wrapper>
</div>
);
})}
{ITEMS.map((item, idx) => {
const ref = createRef();
return (
<div key={idx} ref={ref}>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && <Item parentRef={ref} />}
</Wrapper>
</div>
);
})}
</div>
);
}