0

Here is the brief snippet of my functional component's render method(removed unnecessary code for brevity)

  return (
    <Draggable draggableId={id} index={index}>
      {(provided, snapshot) => (
        <>
          <div className="carditem" ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} onClick={onClick}>
            <span className="carditem_title">{card.title}</span>
            <i className="fas fa-pencil-alt edit_button" onClick={onEditClick} />
            {hasDescription && <i className="fas fa-align-left desc_tag" title="This card has a description" />}
          </div>
          {isEditing && showOverlay && <input className="card_edit" type="text" autoFocus />}
        </>
      )}
    </Draggable>
  );

On line 5, if you notice I have a

ref={provided.innerRef}

I want to get the x,y coordinate of div with className="cardItem" and therefore I want to add a ref to that element. But a ref already exists as shown above. How can I add my own ref variable without breaking existing ref?

Not sure if it helps, but I am using react-beautiful-dnd and which is where that provided.innerRef comes from.

1 Answer 1

1

You can use the callback to bind multiple refs

const refHanlder = el => {
  refA.current = el;
  refB.current = el;
}

ref={el => refHandler}

The callback is also used for Array of refs

ref={el => elementRef.current[x] = el}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. One small question. how do I pass provided.innerRef into refHandler function?
@theprogrammer It's passed implicitly and if you want to make it a param, use ref={el => refHandler(ref)} with const refHanlder = el => () => {

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.