Christoph Berger
Christoph Berger

Reputation: 371

Getting props of a clicked element in React

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>
      )
    })

Upvotes: 3

Views: 1600

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

One simple way is passing the value itself,

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

And the function,

filterProjects = (value) => {
  console.log(value)
}

Upvotes: 6

Related Questions