Sathya
Sathya

Reputation: 1734

How to get tags attribute value in ReactJs?

I have created one small app with reactjs. On button tag I've set one attribute and passing the value. When i click on button need get that attribute value. How to achieve this one with react js?

Sample code,

var React  = require('react');
var CommentWall = React.createClass({
  getInitialState:function(){
    return {
      data:[]
    }
  },
  commentOpen:function(event){
    var targetID = this.state.dataId;
    console.log(targetID);
    $.ajax({
     url:url+"comments/"+targetID,
     type:"GET",
     dataType:"JSON",
     success:function(data){
       this.setState({data:data});
     });
  }
  render:function(){
    var wallCard;
    var commentWall = this.props.data.map(function(el, i){
      wallCard = <div className="card-content">
          <div className="content-inner">{el.LINES}</div>
          <button dataId={el.ID}>Click</button>
        </div>;
      return <div className="card wall-card" key={i}>{wallCard}</div>;
    }.bind(this));
    return (
      <div>{commentWall}</div>
    );
  }
});

module.exports = CommentWall;

Upvotes: 1

Views: 1276

Answers (1)

Aleksandr Petrov
Aleksandr Petrov

Reputation: 1288

State – is not state of element which was clicked, it's state of your CommentWall components, which have only data key. Attribute is not necessary to use. It is not React-way.

You can you closure or simple bind to pass ID into your function.

Example with bind:

var React  = require('react');
var CommentWall = React.createClass({
  getInitialState: function(){
    return {
      data:[]
    }
  },

  commentOpen: function(targetID, event){
    console.log(targetID);
    $.ajax({
     url:url+"comments/"+targetID,
     type:"GET",
     dataType:"JSON",
     success:function(data){
       this.setState({data:data});
     });
  },

  render:function(){
    var wallCard;
    var commentWall = this.props.data.map(function(el, i){
      wallCard = <div className="card-content" onClick={this.commentOpen.bind(this, el.ID)>
          <div className="content-inner">{el.LINES}</div>
          <button>Click</button>
        </div>;
      return <div className="card wall-card" key={i}>{wallCard}</div>;
    }.bind(this));
    return (
      <div>{commentWall}</div>
    );
  }
});

module.exports = CommentWall;

Upvotes: 2

Related Questions