Reputation: 794
I'm really new to ReactJs and currently struggling to create an onClick event, that will take the href value of itself and pass it to a function called 'action'.
The action function should then prevent the default browser behavior, perform a GET request to the passed in URL, and show an alert dialog containing the response and status.
However I am stuck trying to call my function from the onClick event with the following error:
Uncaught (in promise) ReferenceError: action is not defined
var Content = React.createClass({
getInitialState: function() {
return {
teams: []
}
},
componentDidMount: function() {
const makeRequest = () => axios.get("http://localhost:5000/api/teams").then(({ data }) => this.setState({ teams: data }));
this.serverRequest = makeRequest();
this.poll = setInterval(() => {
this.serverRequest = makeRequest();
}, 10000)
},
componentWillUnmount: function() {
this.serverRequest.abort();
clearInterval(this.poll)
},
action: function(e) {
e.preventDefault();
$.get(e.href, function(res, status) {
alert("Response: " + res + "\nStatus: " + status);
});
},
render: function() {
const { teams } = this.state;
return (
<div className="list-group">
{ teams.map(function(team) {
return ([
<a href={ "http://localhost:5000/api/teams?name=" + team.name} onClick={ action }>Click Me</a>
]);
})}
</div>
)
}
});
ReactDOM.render(<Content />, document.getElementById('content'));
Upvotes: 2
Views: 34154
Reputation: 61
In my case, I forgot to require the function. So my suggestion is, please do check the function is imported correctly.
Upvotes: 0
Reputation: 1249
Try this.action
instead of action
.
UPDATE
I found the problem. It is all about scope. You can't access this
inside map
.
render: function() {
const { teams } = this.state;
return (
<div className="list-group">
{ teams.map((team) => {
return ([
<a href={ "http://localhost:5000/api/teams?name=" + team.name} onClick={ this.action }>Click Me</a>
]);
})}
</div>
)
}
Upvotes: 4
Reputation: 104389
Its a binding issue, try this it will work:
render: function() {
const { teams } = this.state;
return (
<div className="list-group">
{ teams.map((team,i)=>{
return <a key={i} href={ "http://localhost:5000/api/teams?name=" + team.name} onClick={ this.action }>Click Me</a>
})
}
</div>
)
}
Suggestion: Whenever creating html elements dynamically, always assign the unique key to each element, key
value will keep your components uniquely identified.
From Facebook React Doc:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
Upvotes: 1