Leahcim
Leahcim

Reputation: 42009

How to get value when React wraps content in spans?

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>

Upvotes: 3

Views: 11009

Answers (2)

enjoylife
enjoylife

Reputation: 3861

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>

Upvotes: 2

Zach Stoltz
Zach Stoltz

Reputation: 223

Also try:

this.refs.content.getDomNode().children[0].textContent

to get the value of the span. (Not sure if there is a react specific function for this). This will have to be done as well as removal of the white space within:

<small ref="date">{date}</small>
<div ref="content">{content}</div>

This is important because react generates span tags to handle the data-reactid. Take a look at: Rid of repeated spans in React.js?.

Upvotes: 2

Related Questions