Search code examples
reactjsreact-hooksuse-refreact-hooks-testing-library

How can I grab multiple mapped elements using useRef?


Here I map though an array of objects that contain images to display on a page. At the moment when I try useRef it only grabs me the very last element. How can I have it so that my useRef grabs me multiple?

  <div className='images-container'>
             {skills.map((skill, idx) => {
                    return <div key={idx}>
                        <img alt={skill.name} ref={imageRef} src={skill.url} />
                        <p>{skill.name}</p>
                    </div>
                })}
            </div>

If I am understanding correctly use ref will only grab one of these elements so I suppose the best approach is to dynamically make different useRefs to grab individually? Sorry, just learning react.


Solution

  • Best solution: don't use refs you probably don't need them. If you tell us why you think you need refs we can verify if you're right.

    Second best, create an array of refs of the same length as your skills list. A ref can only point to one object. What you're doing is placing the same refs on many objects which isn't how refs are designed to work.

    const refs = [];
    for (let i = 0; i < skills.length; i++) {
        refs.push(useRef());
    }
    return (
      <div className='images-container'>
                 {skills.map((skill, idx) => {
                        return <div key={idx}>
                            <img alt={skill.name} ref={refs[idx]} src={skill.url} />
                            <p>{skill.name}</p>
                        </div>
                    })}
                </div>
    )