I have a React component called Home. Within Home, I have a function "urlListener" in which I have added an event listener to alert whenever the URL is being changed.
var Home = React.createClass({
getInitialState: function () {
return {
openedFile: this.props.location.query.file || '',
apps: [],
showNav: this.props.location.query.file ? false : true,
layout: 'row',
cloneAppName: 'New Application',
appName: 'Application Name',
showSave: false
}
},
urlListener: function(){
window.addEventListener("hashchange", function(){
saveUnsaved();
});
},
saveUnsaved: function(){
}
The listener works fine and is being called whenever there is a change in the URL. However, the console says that the function I'm trying to call is not a function. I am new to React and any help on this would be appreciated.
Someone had commented the answer which seemed to work for me, but the comment was removed before I could accept the answer. The correct way of doing it is
{() => this.saveUnsaved();}
The arrow function apparently switches the context from "window" to "this"(the current component) internally. Without the arrow function, "this" would be referring to the "window" component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With