I'm trying use React events
to access a custom 'value' assigned to a button, but I get different results depending on where I click on the button. I can probably use getDOMNode()
or this.state
to get the desired result but I'm little confused on how to use 'React Events' and it's behavior.
Is it best to use synthetic events on a single element like <input>
? Is there a way to get the value of a button using react events?
Note: I'm using bootstrap glyphicon inside the <button>
element.
var Content = React.createClass({
handleClick: function(e) {
console.log( e.target );
},
render: function() {
return (
<div>
<button type="button" value="button1" className="btn btn-default" onClick={this.handleClick}><span className="glyphicon glyphicon-ok"></span> Submit</button>
</div>
)
}
});
Jsfiddle
console.log( e.target ) results:
Move the mouse over the glyphicon 'check mark', and click.
<span class="glyphicon glyphicon-ok" data-reactid=".0.0.0"></span>
Move the mouse over the word 'Submit' and click
<span data-reactid=".0.0.1"> Submit</span>
Move the mouse anywhere else inside the button, and click
<button type="button" value="button1" class="btn btn-default" data-reactid=".0.0"><span class="glyphicon glyphicon-ok" data-reactid=".0.0.0"></span><span data-reactid=".0.0.1"> Submit</span></button>
I'm new to synthetic events and DOM behaviors as you guys can tell. Any guidance would be greatly appreciated! Thanks.
I think you want e.currentTarget.getAttribute('value')
Using currentTarget
will get the button since the event will bubble up to the button. You are getting the span element since you're likely clicking the span. That's what the value of target
is.
Also here is the updated fiddle: http://jsfiddle.net/v27bqL5y/1/
Another way to do this is to use refs. If you want to stay away from using stuff like e.currentTarget
, this can be a simpler way to go.
See the fiddle: http://jsfiddle.net/v27bqL5y/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With