Praveen Mohan
Praveen Mohan

Reputation: 231

How to pass a value from <a> (anchor tag) to a function in react js?

I am trying to create a CRUD application using react and mvc .net. On clicking the edit/delete link in the table, I want the corresponding EmpID to be passed to a function and then it should be passed to a controller, where edit/delete operation happens. Please let me know how to do this.

var EmployeeRow = React.createClass({

    Editnavigate: function(){

    },

    Deletenavigate: function(){

    },

    render: function () {
        return (
            <tr>
                <td>{this.props.item.EmployeeID}</td>
                <td>{this.props.item.FirstName}</td>
                <td>{this.props.item.LastName}</td>

                <td>
                    <a href="#" data-value="this.props.item.EmployeeID" onclick=this.Editnavigate>edit</a> | 
                    <a href="#" data-value="this.props.item.EmployeeID" onclick=this.Deletenavigate>delete</a>
                </td>               
            </tr>

        );
    }
});

Upvotes: 2

Views: 7757

Answers (3)

Ajay Singh
Ajay Singh

Reputation: 501

You can do it as below. I was trying the same in reactjs with javascript(ES-6), but nothing else worked except for below-

<a href = 'www.google.com' onClick={clickHandler} > Google </a>

clickHandler(event){
  event.preventDefault();
  alert("This is alert: " + event.target.getAttribute('href'));
}

Here event.target.getAttribute('href') will return 'www.google.com'

Upvotes: 0

Vivek Doshi
Vivek Doshi

Reputation: 58593

You can do it by using onClick, as simple as this

Editnavigate (e,id) {
    e.preventDefault();
    alert(id);
}

<a href="#" onClick={(e) => this.Editnavigate(e,1)}>edit</a> // pass your id inplace of 1

WORKING DEMO

Note : You can also pass via data-value , but still that's not good idea, in that case you still need to access dom and fetch via that field, instead that just pass the value when its possible. That will be simple and requires less processing.

Upvotes: 3

Mark
Mark

Reputation: 11018

You could retrieve the data you want from your click handlers like this:

EditNavigable: function(e) {
    var clickedLink = e.currentTarget;
    var data = clickedLink.getAttribute('data-value');
}

Or you could put it into it's own function like so:

getDataValue: function(e) {
    return e.currentTarget.getAttribute('data-value');
}

and then call it from your edit and delete functions like this:

EditNavigable: function(e) {
    var data = this.getDataValue(e);
} 

Upvotes: 0

Related Questions