Reputation: 33
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 [];
}
Upvotes: 2
Views: 3547
Reputation: 737
As Emil H mentioned in the comments above, the issue is that this
is not bound once you enter the map
function. You can either pass the thisArg
to the map function, or move that function to a separate class function that you bind in your constructor. That would look something like this (untested):
class Upcoming_Training extends Component {
constructor(props) {
super(props);
this.filterCourses = this.filterCourses.bind(this);
this.renderCourseRow = this.renderCourseRow.bind(this);
}
showDate(date) {
// Format date...
}
renderCourseRow(course, index) {
return (
<tr key={index}>
<th><button className='btn btn-sm btn-primary'> More Info </button></th>
<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>
)
}
filterCourses() {
if (this.props.upcoming_training != []) {
return this.props.upcoming_training.map(renderCourseRow);
}
return [];
}
// ...Rest of component
}
Upvotes: 4
Reputation: 315
First remove comma after inputValue: '',
in the this.state declaration. Also in your filterCourses function the if(this.showDate)
condition is looking for a showDate property not a function. You function showDate also expects a date.
You also need a render function as any react component is required to have one.
Upvotes: -1