I have bound this handleRemove in the constructor but the below code does not work for some reason
handleRemove()
{
//console.log(e.target.value)
console.log('click')
}
<button key={index} onClick={this.handleRemove}>X</button>
The error I get:
TypeError: Cannot read property 'handleRemove' of undefined
Even when I remove binding and use arrow functions, () => this.handleRemove(), I get the same error. Anyone have a solution?
The full component:
class ScheduleList extends Component
{
constructor(props)
{
super(props);
this.state = {
"actions": [],
"thingsDue" : []
}
this.componentDidUpdate = this.componentDidUpdate.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
//this.handleRemove = this.handleRemove.bind(this);
}
componentDidMount(e)
{
fetch("http://localhost:5000/backend/" + this.props.date).then(res => res.json()).then(resjson => {
this.setState({actions: JSON.parse(resjson)})
}).catch(err => console.log(err))
fetch("http://localhost:5000/backend/due/" + this.props.date).then(res => res.json()).then(resjson => {
this.setState({thingsDue: JSON.parse(resjson)})
}).catch(err => console.log(err))
}
componentDidUpdate(prevProps) {
if (this.props.date !== prevProps.date)
{
fetch("http://localhost:5000/backend/" + this.props.date).then(res => res.json()).then(resjson => {
this.setState({actions: JSON.parse(resjson)})
}).catch(err => console.log(err))
fetch("http://localhost:5000/backend/due/" + this.props.date).then(res => res.json()).then(resjson => {
this.setState({thingsDue: JSON.parse(resjson)})
}).catch(err => console.log(err))
}
}
handleRemove()
{
//console.log(e.target.value)
console.log('click')
}
render()
{
let listItems = this.state.actions.map((dic, index) => <li key={index}>{"From " + dic.start.toString() + " - " + dic.end.toString() + ": " + dic.activity}</li>)
listItems = listItems.map(function(elem, index) {
return [elem, <button key={index} onClick={() => this.handleRemove()}>X</button>]
})
let dueItems = this.state.thingsDue.map((dic, index) => <li key={index}>{dic.thing_due}</li>)
let timeSpent = 0;
for(var index = 0; index < this.state.actions.length; index++)
{
timeSpent += (this.state.actions[index].end - this.state.actions[index].start);
}
dueItems = dueItems.map(function(elem, index) {
return [elem, <button key={1000 * index + 1000}>X</button>]
})
return (
<div>
<ul>
{listItems}
</ul>
<p>{"Productive hours: " + timeSpent}</p>
<b>Things Due</b>
<ul>
{dueItems}
</ul>
</div>
)
}
}