GBarroso GBarroso - 7 months ago 12
Javascript Question

React: Is it possible to access a DOM element's props?

Yo, hello there, I'm pretty new to react. I've noticed many people binding

this
to their DOM's elements functions.

Let's say I have a component with:

render(){
<div>
<button onClick={this.doSomething.bind(this)} test={someObj}></button>
</div>
}

doSomething(){
this.props.whatever();
}


Now, In my mind it made sense having
this
bound to
this.doSomething
, because otherwise
this
would be the button component object, and the this.props would be relative to the button's props, which is something I don't want.

So I got caught in a situation where I wanted to get something from the button's props (the
test
object). What I thought I could do: remove the
bind(this)
from the call, so
this.props
would be the button's props. But when I call
this.doSomething
without using bind,
this
is returning null (maybe I'm messing this up somehow).

I guess my logic is flawed then. I would like to know what's the real purpose of binding
this
to the handlers and if there's a way that I can access a DOM element's props (or at least, how can I get the
test
in the example)

Thanks in advice!

Answer

You can store data-value in button as follows:

 render(){
<div>
    <button  data-value="item1" onClick={this.doSomething.bind(this)} test={someObj}></button>
</div>

}

And access using this:

doSomething(event){
console.log(event.target.dataset.value)
this.props.whatever();
}