0

I wrote a demo here:

import React, { useRef, useEffect, useState } from "react";
import "./style.css";

export default function App() {
  // let arrRef = [useRef(), useRef()];

  let _data = [
    {
      title: A,
      ref: null
    },
    {
      title: B,
      ref: null
    }
  ];

  const [data, setData] = useState(null);

  useEffect(() => {
    getDataFromServer();
  }, []);

  const getDataFromServer = () => {

    //assume we get data from server

    let dataFromServer = _data;
    dataFromServer.forEach((e, i) => {
      e.ref = useRef(null)
    });
  };

  return (
    <div>
  {
//will trigger some function in child component by ref
    data.map((e)=>(<div title={e.title} ref={e.ref}/>))

  }
    </div>
  );
}


I need to preprocess after I got some data from server, to give them a ref property. the error says 'Hooks can only be called inside of the body of a function component' . so I checked the document, it says I can't use hooks inside a handle or useEffect. so is there a way to achieve what I need?

update: I need to create component base on DB data, so when I create a component I need to give them a ref , I need trigger some function written in child component from their parent component and I use ref to achieve that. that is why I need to pass a ref to child component.

jjzjx118_2
  • 419
  • 7
  • 23
  • 2
    I think the main problem is calling `useRef` in the `forEach` callback. For hooks to work, the same hooks have to be called in the same order and that is not given if you run a hook in a loop (since the loop condition might change between renders). Why are you doing this? Maybe if we know what you are trying to achieve we can suggest another approach. – Felix Kling Apr 14 '21 at 18:42
  • Hi @FelixKling I add the reason why I need ref in my question – jjzjx118_2 Apr 14 '21 at 19:06
  • Duplicate - https://stackoverflow.com/a/37950970/15304814 - you are trying to access a child components function in the parent. – Sean W Apr 14 '21 at 19:16
  • Does this answer your question? [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Sean W Apr 14 '21 at 19:28
  • @SeanW what I am doing is using the forwardRef and useImperativeHandle. the problem is I need to give ref dynamically, so I can't define useRef() in the component body in advance. – jjzjx118_2 Apr 15 '21 at 02:23
  • Can you show how you're using the ref? Why is there a ref attached to div? Why do you need access to the DOM node? It doesn't sound like how you are trying to do this is the best way. – Sean W Apr 15 '21 at 03:30
  • @SeanW I found a solution in the question that you pasted, bind functino to parent function on child loaded. thank you. – jjzjx118_2 Apr 15 '21 at 15:30

0 Answers0