Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ID from div in React.js

So I'm trying to retrieve data in a div attribute in react. JSFiddle shows the problems I'm having. this.state.value is set to an empty string after the event fires.

I started off using the data-* attribute for the div after reading another stack overflow post, but I cannot use jQuery, so I switched to id. Any ideas?

JSFiddle

class GettingAttributes extends React.Component {
  constructor(props) {
    super(props)
    this.state = {value: 'Hello!'};

    this.bar = this.bar.bind(this);
  }

  bar(e){
    this.setState({value: e.target.id})
  }

  render() {
    return (
      <div id="foo" onClick={this.bar}>
        <p>{this.state.value}</p>
      </div>
    );
  }
}
like image 236
Joe Spalding Avatar asked Oct 20 '25 22:10

Joe Spalding


1 Answers

Use

e.currentTarget.id

instead of

e.target.id

.currentTarget will target the element that actually contains the event listener. In your scenario, .target is the p tag with the text in it, which doesn't have an id to set in your state.

like image 126
Ryan Avatar answered Oct 23 '25 13:10

Ryan