chrisrhyno2003
chrisrhyno2003

Reputation: 4177

React - Get text of div on click without refs

Is there an example where we can retrieve the value of a React element without the usage of refs? Is that possible?

var Test = React.createClass({

  handleClick: function() {
    alert(this.text);
  },
  render: function() {
    <div className="div1" onClick={this.handleClick}> HEkudsbdsu </div>
  }
})

Upvotes: 18

Views: 51451

Answers (5)

Muhammad Usman
Muhammad Usman

Reputation: 173

This worked for me You can use innerText , innerHtml or textContent

Upvotes: 2

dimpiax
dimpiax

Reputation: 12677

If you want to retrieve text, use innerText property, if html – innerHTML.

Example:

handleClick: function(e) {
  alert(e.currentTarget.innerHTML);
}

Upvotes: 2

Ikram Ud Daula
Ikram Ud Daula

Reputation: 1321

Try this way.

handleMenuItemClick = (event) => {
  console.log(event.target.textContent);
};

<option onClick={event => this.handleMenuItemClick(event)}>
  item
</option>

Upvotes: 4

chrisrhyno2003
chrisrhyno2003

Reputation: 4177

I found a working answer:

var Hello = React.createClass({
  handleClick: function(event) {
    alert(event.currentTarget.textContent);
  },
  render: function() {
    return <div className="div1" onClick={this.handleClick}> HEkudsbdsu </div>
  }
});

Upvotes: 48

MattDiamant
MattDiamant

Reputation: 8771

I suppose you can just get the DOM Node with ReactDOM.findDOMNode(this);, and then get its innerText or whatever you need from it.

var Hello = React.createClass({
  handleClick: function() {
    var domNode = ReactDOM.findDOMNode(this);
    alert(domNode.innerText);
  },
  render: function() {
    return <div className="div1" onClick={this.handleClick}> HEkudsbdsu </div>
  }
});

This is a bit of a runabout way of doing it, but it will work.

Note that pre 0.14 React, you'll just be using React and not ReactDOM.

Upvotes: 6

Related Questions