Louis Sankey
Louis Sankey

Reputation: 492

React - get DOM element TEXT value with Ref

This should be a simple operation, but everything I keep finding online is how to get an 'input value' with a react ref.

I need to know how to get a TEXT value from a DOM element like

<p>hello world</p>

and get 'hello world'

I have the ref set properly and I can log the full html tag with refName.current.

To get the text I have tried refName.value, refName.current.value refName.text, refName.current.text(), refName.innerText.. etc.

Can anyone point me in the right direction?

Thanks.

Upvotes: 0

Views: 7048

Answers (2)

munshots
munshots

Reputation: 1

textContent is preferred over innerText:

ref?.current?.textContent

Upvotes: 0

JAM
JAM

Reputation: 6205

You can access the text via ref.current.innerText

For example (sandbox):

  const ref = useRef();

  useEffect(() => {
    console.log(ref.current?.innerText || "ref not set!");
  }, []);

  return <p ref={ref}>Hello world</p>;

Keep in mind that the ref.current is not set for the first render - so it is undefined to start with.

Upvotes: 0

Related Questions