reactjsref

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.


Solution

  • 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.