0

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;
LismUK
  • 119
  • 1
  • 8

1 Answers1

6

Javascript functions declared with function keyword has their own this context, so this inside this.props.shows.map( function(show, i) does not refer to the class. You can use arrow syntax for function declaration which will laxically resolve value of this. Change

this.props.shows.map(function(show, i)

to

this.props.shows.map((show, i ) => {
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
  • 1
    Oh wow, that's an annoying little gotcha for people new to JS. Thanks a lot, I'll keep that in mind when writing my JSX. – LismUK Feb 13 '18 at 17:17