I have been researching this topic for a while and am completely stuck. I am using React.js
, and using an es6 class component.
When I call this.showDate
inside of my filterCourses
function it is claiming that it can't read the showDate
property of undefined
. This means the keyword this
is undefined
.
I have tried binding this
in the constructor.
Question
How do I make this
defined?
class Upcoming_Training extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
}
}
componentDidMount() {}
showDate(date) {
// Creates a more readable date
if (date) {
date = date.substring(0, date.indexOf("T"));
let dateArr = date.split('-');
return dateArr[1] + '/' + dateArr[2] + '/' + dateArr[0];
}
}
filterCourses() {
let courseRows = [];
if (this.props.upcoming_training != []) {
if (this.showDate) {
let courseRows = this.props.upcoming_training.map(function (
course, index) {
return <tr>
<th><button className='btn btn-sm btn-primary'> More Info </button></th> {/*Will make this button do something later*/}
<td>{course.Course}</td>
<td> {(course.Name.includes("OL -") ? course.Name.slice(5) : course.Name)}</td>
<td>{this.showDate(course.Start)}</td>
<td>{this.showDate(course.End)}</td>
<td>{(course.IsOnline ? "Online" : "On-Site")}</td>
</tr>
})
}
return courseRows;
}
return [];
}
this.filterCourses = this.filterCourses.bind(this)
to your constructor?this
keyword. So you would need it infilterCourses
, but not inshowData
, since you never usethis
in that function.this.props.upcoming_training.map
, That map as defined in developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… takes athisArg
and since you are not providing one it will beundefined
. That causes thethis
inthis.showDate
to beundefined
. Either bindingshowDate
or providing a thisArg should aleviate the problem.