Ad

How To Get Value When React Wraps Content In Spans?

- 1 answer

I have a React component that renders some html like below, with one callback method (this.deleteItem) triggered upon click of an x. In the callback method, I try to get the content associated with each of the two refs like this

var date = this.refs.date.getDomNode.value;
var content = this.refs.content.getDomNode.value;

but the result is undefined in both cases. When I simply do this.refs.content.getDomNode (instead of looking for the value) it shows me a div with some span tags inside, and inside of one of those is the content I was seeking. Similarily with the date ref, it is a <small></small> element with spans inside.

Question: how to get the value/content from a div or element when react wraps content in spans?

<div ref="wrapperdiv">
  <span className="delete" onClick={this.deleteItem}>x</span>
  <small ref="date"> {date} </small>
  <div ref="content"> {content } </div>
</div>
Ad

Answer

This is a known limitation of react, in that it wraps any floating text nodes in a span because it has to handle the data-reactid of the component. See this question too.

Perhaps if you tried to remove the white space around the content?

<div ref="wrapperdiv">
  <span className="delete" onClick={this.deleteItem}>x</span>
  <small ref="date">{date}</small>
  <div ref="content">{content}</div>
</div>
Ad
source: stackoverflow.com
Ad