Search code examples
javascriptarraysreactjsref

ref not referencing correct item in array


This issue probably arises from my lack of understanding of refs. I have this container that I am rendering from an array.

Lets say it will render 4 containers. Each container will have 3 links. When I hover over the one of the links a clipboard icon becomes visible. Using react-copy-to-clipboard library I copy the contents of the that particular item to the clipboard. However, my issue is that it is only copying the last item of the 4th container instead of the one I hovered over or chose. I feel it might also have to do with the index?

I hope someone can clarify why this is happening and help me find a solution.

    handleMouseEnter = index => {
    this.setState(prevState => ({
        isHovered: {
            ...prevState.isHovered,
            [index]: true,
        },
        ref: this.textRef.current.attributes.label.nodeValue,
    }));
};


<LinkContainer className="linkContainer">
  {links.map(({ name, path }, index) => (
    <ul className="styledLinks">
       <li
          onMouseEnter={() => this.handleMouseEnter(index)}
          onMouseLeave={() => this.handleMouseLeave(index)}
       >
       <StyledLinks
         key={name}
         ref={this.textRef}
         value={name}
         label={path}
       />
         {isHovered[index] && (
           <CopyToClipboard
             onCopy={this.copy}
             text={ref}
           >
           <StyledCopyIcon
            icon="copy"
            className="copyIcon"
            copySucces={copySuccess}
            onClick={this.setCopySuccess}
           />
           </CopyToClipboard>
          )}
        </li>
      </ul>
    ))}
  </LinkContainer>

Solution

  • You always overwrite the same ref in your loop:

    ref={this.textRef}
    

    So the last loop iteration will overwrite the ref with the last element, and all click handlers will reference that.

    You should create an individual ref for each element. There's some suggestions for how to do this on this Github issue.