Mukhammad Ali
Mukhammad Ali

Reputation: 850

All child elements inheriting onclick event from parent div on React

This is my code on return section. All children elements is ineriting click events and when I click it is giving me the object of that child element not parent.

return (
  <div className={css(style.cell)} onClick={this.props.onClickHandle}>

      <div className={css(style.image)}>
        <CircleImage size={50} url = {"http://www.ruralagriventures.com/wp-content/uploads/2017/05/man-team.jpg"}/>
      </div>

      <div className={css(style.info)}>

        <div className={css(style.profile)}>
          <span>{this.props.name}</span>
          <span className={css(style.lastMessage)}>Latest Message</span>
        </div>

        <div className={css(style.detail)}>
          <span>a few seconds ago</span>
          <span className={css(style.counter)}>5</span>
          </div>
      </div>
  </div>
)

I only want an object from parent div, not children. Before passing props I assigned this.onClickHandle = this.onClickHandle.bind(this);

Upvotes: 1

Views: 2738

Answers (1)

Piyush Dhamecha
Piyush Dhamecha

Reputation: 1515

You can use refs, refer this link

onClickHandle(e){
    this.parentDiv //parent object
}

return (
  <div ref={(parentDiv) => { this.parentDiv = parentDiv; }} className={css(style.cell)} onClick={this.props.onClickHandle}>

      <div className={css(style.image)}>
        <CircleImage size={50} url = {"http://www.ruralagriventures.com/wp-content/uploads/2017/05/man-team.jpg"}/>
      </div>

      <div className={css(style.info)}>

        <div className={css(style.profile)}>
          <span>{this.props.name}</span>
          <span className={css(style.lastMessage)}>Latest Message</span>
        </div>

        <div className={css(style.detail)}>
          <span>a few seconds ago</span>
          <span className={css(style.counter)}>5</span>
          </div>
      </div>
  </div>
)

Upvotes: 1

Related Questions