0

In my application I have two components, let's say Component1 and Component2, and a third component in charge of rendering the two.

Inside the third component, at the root level, I have an array that contains options among the 2 components, which look like this:

const RenderingComponent = () => {
  const ref1 = useRef();
  const ref2 = useRef();
  
  const array = [{
    title: '#1',
    component: <Component1 ref={ref1} />,
    ...
  }, {
    title: '#2',
    component: <Component2 ref={ref2} />
    ...
  }];

  ...
}

Now, what happens is that Component1 gets initialized whilst Component2 doesn't. I tried to switch the order in the array and the exact other way round happens: Component2 gets initialized and Component1 doesn't.

I can confirm this since:

  1. I put console logs at the root level in the two Components and only the logs of the first component in the array work.
  2. The ref assigned to the second Component in the array always gives undefined on ref.current

PS: Both the components use forwardRef + useImperativeHandle to expose some methods.

Does anyone know what is happening here?

ThomasSquall
  • 644
  • 6
  • 21
  • 6
    You haven't given us any information around how you are _rendering_ these components (or your application). How does `array` get used in the render? Are you rendering `array.map(v => v.component)`? – romellem Jul 13 '23 at 15:25
  • 2
    Please provide a [mre] that can be run directly to see the issue. There is not enough information currently. – Unmitigated Jul 13 '23 at 15:26
  • Does this help? https://stackoverflow.com/questions/54633690/how-can-i-use-multiple-refs-for-an-array-of-elements-with-hooks – PAB Jul 13 '23 at 16:01
  • Hello everyone I appreciate your intervention. I didn't give any information about rendering because what I'm asking is why it is not getting initialized and not rendered. Anyway yes, I use an array.map to render the components. Thanks – ThomasSquall Jul 13 '23 at 16:25
  • @PAB I am not able to test right now, I will test later and let you know! Thanks – ThomasSquall Jul 13 '23 at 16:26
  • The other component isn't initialized, because you probably made a mistake while rendering them. You should show your code – Konrad Jul 13 '23 at 16:30
  • The code where `useImperativeHandle` is used might be of interest. – NotX Jul 13 '23 at 18:25
  • 1
    @ThomasSquall You might not realize it, but the initialization of the refs and how the components are being rendered are very much related. This is why you should create a [mre] that shows the issue and add it to the question. This makes it easier to pinpoint where the exact issue is. Do not remove so much context that the issue is not reproducible anymore. – Unmitigated Jul 14 '23 at 12:16

0 Answers0