0

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>
2
  • What is ref ? you're setting the copy text to that every time Commented Nov 8, 2018 at 16:59
  • Sorry, that was not clear enough. I am storing the ref to state based on the onMouseEnter then I am using that this.state.ref to copy as text. That is the incorrect text though, always grabs the same one. @AndyRay Commented Nov 8, 2018 at 17:05

1 Answer 1

1

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.

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.