Anto Anto - 2 months ago 17
Javascript Question

Uncaught TypeError in React component

I have created this small and simple script containing a React component:

var React = require('react');


var UsersList = React.createClass({

handleRedirection: function(userName){
window.location = '/user/'+userName;
},
render: function(){
return(
<table>
<tbody>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Day of Birth</th>
<th>Username</th>
<th>Role</th>
<th></th>
</tr>
{this.props.content.map(function(user, i) {
return (
<tr key={i}>
<td>{user.name}</td>
<td>{user.surname}</td>
<td>{user.birthday}</td>
<td>{user.userName}</td>
<td>{user.userRole}</td>
<td><button onClick={this.handleRedirection(user.userName)}>Open</button></td>
</tr>
);
})}
</tbody>
</table>
)
}
})


module.exports = UsersList;


When compiling, I do get in the browser the following error:


Uncaught TypeError: this.handleRedirection is not a function


I believe everything seems correct with the way the function is called, where the problem may be?

Answer

you need to bind this to function:

{this.props.content.map(function(user, i) {
  return (
    <tr key={i}>
      <td>{user.name}</td>
      <td>{user.surname}</td>
      <td>{user.birthday}</td>
      <td>{user.userName}</td>
      <td>{user.userRole}</td>
      <td><button onClick={this.handleRedirection.bind(null, user.userName)}>Open</button></td>
    </tr>
  );
}.bind(this))}
Comments