4

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 component 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>
      );
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
aaaania
  • 73
  • 1
  • 1
  • 5

1 Answers1

4

Here 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>
  );
}
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31