Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text content from node in React

Tags:

dom

reactjs

Having a bit of trouble pulling text from a node.

The node is a paragraph.

 <p className="Blend" refs="hello"> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>

I’m trying to log the contents of the node to the console in a function.

 makeSmall = () => {
        var text = this.refs.hello.innerText
        console.log(text)
      }

However, this console is not returning anything. I've tried accessing the node with via className as well.

What's the proper way to access text in React?

like image 644
frente_fin Avatar asked May 19 '18 19:05

frente_fin


2 Answers

react-getNodeText Sandbox screenshot

const getNodeText = node => {
  if (['string', 'number'].includes(typeof node)) return node
  if (node instanceof Array) return node.map(getNodeText).join('')
  if (typeof node === 'object' && node) return getNodeText(node.props.children)
}

const printHTML = ref => ref && (ref.innerText = document.querySelector('h1').outerHTML)

https://codesandbox.io/s/react-getnodetext-h21ss

  // in the picture
  {heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
  <pre ref={printHTML}/>
  <pre>{getNodeText(heading)}</pre>

originally from here https://stackoverflow.com/a/60564620/985454

like image 70
Qwerty Avatar answered Sep 28 '22 19:09

Qwerty


Thanks to everyone for contributing. There were a few mistakes in my previous approach.

Namely, trying to set the ref in a function. Below are the steps I took to make it work.

1) construct the ref using React.createRef(); (new in react 16)

class Newone extends Component {
    state = {
        allocation: "Acq",
      };
      textUrl = React.createRef();

2) append the ref to the appropriate node

 <p className="Blend" ref={this.textUrl}> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>

3) reference the ref using value.innertext

handleLinkClick = (event) => {
bitly.shorten(this.textUrl.value.innerText) 

**Make sure you are using React version 16.3.0-alpha.1.

Below are screenshots of the console.

bitly.shorten(this.textUrl) enter image dfs here

bitly.shorten(this.textUrl.value) enter image description here

bitly.shorten(this.textUrl.value.innerText) enter image description here

Make sure to append innerText if you only want to return the text in the node.

Hope this helps

like image 42
frente_fin Avatar answered Sep 28 '22 18:09

frente_fin