0

I have a gallery component that takes in an array of components. In each of the child components I am assigning a ref. The reason for this is because within the child component there are many other children components and I am attempting to access some functions on a component that is about 5 component deep. The below code shows the initial setup:

export class Gallery extends React.Component {
    render() {
        const galleryItems = data.map((item, index) => {
            return (
                <GalleryItem
                    ref={React.createRef()}
                />
            );
        });

        return (
            <div >
                <Gallery
                    items={heroGalleryItems}
                />
            </div>
        );
    }
}

When the Gallery component renders all the refs in the array of GalleryItem component are correct. But as soon as the Gallery component re renders for any reason the refs in the GalleryItem components become null values.

I have tried several things in the children components but nothing I do fixes the issue. I believe the reason is because something is happening in the code above.

I have also tried to change up the code after reading the following:

Issue storing ref elements in loop

However its not really clear to me what the person is saying to do when I look at my own implementation.

3
  • give key={index} to the <GalleryItem /> in the loop, and let me know if it works? Commented Nov 20, 2018 at 18:54
  • My. apologies, I was holding back some of the code because of our company limitations. There is a prop key={index} Commented Nov 20, 2018 at 18:56
  • After reading the other post I was sure there was some kind of syntax that would easily solve this. Commented Nov 20, 2018 at 18:56

1 Answer 1

1

You need to move out React.createRef() from the loop (and also render) as it is creating a new ref on every render.

Depending on your code/usage, you'd need to do this in constructor and CWRP methods (basically whenever data changes).

Then creating galleryItems would be like

...
<GalleryItem ref={item.ref} />
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.