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?
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
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)
bitly.shorten(this.textUrl.value)
bitly.shorten(this.textUrl.value.innerText)
Make sure to append innerText if you only want to return the text in the node.
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With