Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting props of a clicked element in React

Tags:

reactjs

Currently learning React and need to get a prop of a clicked element. I managed to get it, but it does not feel like the "right" react way.

This is what I have (it works):

filterProjects = (event) => {
  const value = event.currentTarget.getAttribute("filterTarget")
  console.log(value)
}

Initially I tried multiple things, e.g.: const value = this.props.filterTarget or const value = event.currentTarget.this.props.filterTarget or even using ref but all returned undefined when console logging the value.

(Using this.props as it's part of a class Component.)

This is what my target element looks like:

const categories = data.allPrismicProjectCategory.edges.map((cat, index) => {
      return (
        <a
          key={index}
          onClick={this.filterProjects}
          filterTarget={cat.node.uid}
        >
          {cat.node.data.category.text}
        </a>
      )
    })
like image 468
Christoph Berger Avatar asked Jan 28 '26 19:01

Christoph Berger


1 Answers

One simple way is passing the value itself,

onClick={() => this.filterProjects(cat.node.uid)}

And the function,

filterProjects = (value) => {
  console.log(value)
}
like image 142
ravibagul91 Avatar answered Jan 31 '26 11:01

ravibagul91



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!