''$' is not defined no-undef reactjs ajaxcall [duplicate]
I was trying to display json data in a table format based on this answer. Everytime I run this, it shows this error Line 15: '$' is not defined no-undef
. I am starting the ajax call in line 15. I've tried adding const $ = window.$;
on the top of the code, but that doesn't solve anything.
class App extends React.Component {
constructor(){
super()
this.state = {
data: []
}
}
componentDidMount() {
$.ajax({
url: "http://www.mocky.io/v2/5c3f2a6c3500004d00ec3789",
type: "GET",
dataType: 'json',
ContentType: 'application/json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(jqXHR) {
console.log(jqXHR);
}.bind(this)
})
}
render() {
return (
<table>
<tbody>{this.state.data.map(function(item, key) {
return (
<tr key = {key}>
<td>{item.name}</td>
<td>{item.post}</td>
<td>{item.country}</td>
<td>{item.contact}</td>
</tr>
)
})}</tbody>
</table>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Any help with the error?
Solution 1:[1]
When using create-react-app, First You need to install the Jquery package like this.
For Mac
sudo npm install jquery --save
For Windows
npm install jquery --save
Now in the JS files you can use jquery
import $ from 'jquery';
Solution 2:[2]
You need to include jQuery library.
import $ from 'jquery';
make sure jquery package is installed.
Solution 3:[3]
You might not even need jQuery in React, the fetch
API exposes by the browser just works fine. Rather than installing the entire jQuery library to just handle Ajax request, I would go instead with axios
which in my opinion is lightweight than jQuery.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Just code |
Solution 3 | tbuglc |