Jquery in React is not defined
Solution 1
Try add jQuery
to your project, like
npm i jquery --save
or if you use bower
bower i jquery --save
then
import $ from 'jquery';
Solution 2
I just want to receive ajax request, but the problem is that jQuery is not defined in React.
Then don't use it. Use Fetch and have a look at Fetch polyfill in React not completely working in IE 11 to see example of alternative ways to get it running
Something like this
const that = this;
fetch('http://jsonplaceholder.typicode.com/posts')
.then(function(response) { return response.json(); })
.then(function(myJson) {
that.setState({data: myJson}); // for example
});
Solution 3
It happens mostly when JQuery
is not installed in your project.
Install JQuery in your project by following commands according to your package manager.
Yarn
yarn add jquery
npm
npm i jquery --save
After this just import $
in your project file.
import $ from 'jquery'
Solution 4
Isn't easier than doing like :
1- Install jquery in your project:
yarn add jquery
2- Import jquery and start playing with DOM:
import $ from 'jquery';
Machycek
Updated on July 05, 2022Comments
-
Machycek almost 2 years
Hi I just want to receive ajax request, but the problem is that jquery is not defined in React. React version is
14.0
Error message
Uncaught ReferenceError: $ is not defined
I have two files :
index.js
import React from 'react'; import { render } from 'react-dom'; import App from './containers/App'; const root = document.getElementById('root'); render( <App source='https://api.github.com/users/octocat/gists' />, root );
app.js
import React, { Component } from 'react'; export default class App extends Component { componentDidMount() { const { source } = this.props; console.log($); // throws error } render() { return ( <h1>Hey there.</h1> ); } }
-
Michael almost 6 yearsIf you are using typescript with react, then use
import * as $ from 'jquery';
instead. more info here stackoverflow.com/questions/35310361/… -
boandriy about 5 yearsIf you will get an error, try running: 1. yarn install. 2.yarn upgrade. 3.yarn add yarn. it solved all the problems for me.
-
Emile Bergeron about 5 yearsThanks for the answer, this was really missing from this thread!
-
Adrian B about 2 yearsI get this error at the runtime: Uncaught TypeError: Cannot define property jQuery360080900754312289092, object is not extensible