imback0526
imback0526

Reputation: 204

React: cannot access div element's value

When I press on the that element I want to log it's attributes(value). I think, I am not using useRef hook correctly.

Link: https://codesandbox.io/s/access-dom-element-forked-lphg6?from-embed=&file=/src/App.js:0-405

import "./styles.css";
import { useRef } from "react";

export default function AccessingElement() {
  const elementRef = useRef();
  const fake_data = ["hello", "bye", "yes", "no"];

  return (
    <div>
      {fake_data.map((item, idx) => (
        <div value={item} ref={elementRef} key={idx} onClick={() => console.log(elementRef.current)}>
          {item}
        </div>
      ))}
    </div>
  );
}

Upvotes: 0

Views: 248

Answers (2)

Tyler Durden
Tyler Durden

Reputation: 1070

The issue is being seen because all the items are being assigned to the same ref. Hence, on clicking any element, text corresponding to the last assigned item (i.e no) gets logged.

In this case, an array of refs needs to be maintained, such that each ref in the array corresponds to an item. Something like this :

import "./styles.css";
import { useRef } from "react";

export default function AccessingElement() {
  const elementRef = useRef([]);
  const fake_data = ["hello", "bye", "yes", "no"];
  return (
    <div>
      {fake_data.map((item, idx) => (
        <div 
            ref={el => elementRef.current[idx] = el}
            key={idx} 
            onClick={() => console.log(elementRef.current[idx])}>
          {item}
        </div>
      ))}
    </div>
  );
}

Here is the working CodeSandbox Link

Upvotes: 1

Chuck
Chuck

Reputation: 804

You can not set value for the div. If you want to set some data for the div, you can do like this.

<div data-val={item} ref={elementRef} key={idx} 
          onClick={() => console.log(elementRef.current.dataset.val)}>
          {item}
</div>

If you want to get the text inside the div, you just need to use textContent

elementRef.current.textContent

Upvotes: 1

Related Questions