1

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?

Proteeti Prova
  • 1,079
  • 4
  • 25
  • 49

3 Answers3

11

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';
Udara Kasun
  • 2,182
  • 18
  • 25
1

You need to include jQuery library.

import $ from 'jquery'; 

make sure jquery package is installed.

Just code
  • 13,553
  • 10
  • 51
  • 93
Fotis Papadamis
  • 184
  • 3
  • 14
1

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.

tbuglc
  • 390
  • 2
  • 10