Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Events behavior

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:

  1. Move the mouse over the glyphicon 'check mark', and click.

    <span class="glyphicon glyphicon-ok" data-reactid=".0.0.0"></span>
    
  2. Move the mouse over the word 'Submit' and click

    <span data-reactid=".0.0.1"> Submit</span> 
    
  3. 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.

like image 210
sajinshrestha Avatar asked Mar 18 '23 13:03

sajinshrestha


2 Answers

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/

like image 164
Gohn67 Avatar answered Mar 26 '23 03:03

Gohn67


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/

like image 43
Chris Houghton Avatar answered Mar 26 '23 02:03

Chris Houghton