Hey guys I'm trying to render a table in react which sets a row as selected in the state when it is clicked.
I'm getting an error like this when the row is clicked: Uncaught TypeError: Cannot read property 'setSelected' of undefined
There are loads of questions about this and the solution seems to be to add the line this.setSelected = this.setSelected.bind(this);
to the constructor so that the function is actually accessible.
I already knew to do that and as you can see below, I've done it and it's still giving me the error. I'm completely stumped.
import React, { Component } from 'react';
class ShowsList extends Component {
constructor(props) {
super(props);
this.state = {selected: {showID: null, i: null}};
this.setSelected = this.setSelected.bind(this);
}
setSelected(event, showID, i) {
this.setState({
selected: {showID, i}
});
console.log(this.state.selected);
}
render() {
return (
<div className="shows-list">
<table className="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Location</th>
<th scope="col">Date</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{this.props.shows.map( function(show, i) {
return (
<tr
key={i}
onClick={(e) => {this.setSelected(e, show._id, i)}}>
<td>{i+1}</td>
<td>{show.eventName}</td>
<td>{show.location}</td>
<td>{show.date}</td>
<td>{show.startTime}</td>
</tr>);
})}
</tbody>
</table>
</div>
);
}
}
export default ShowsList;