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>
);
}
}
Try add jQuery to your project, like
npm i jquery --save
or if you use bower
bower i jquery --save
then
import $ from 'jquery';
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'
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
});
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';
Just a note: if you use arrow functions you don't need the const that = this part.
It might look like this:
fetch('http://jsonplaceholder.typicode.com/posts')
.then((response) => { return response.json(); })
.then((myJson) => {
this.setState({data: myJson}); // for example
});
Add "ref" to h1 tag :
<h1 ref="source">Hey there.</h1>
and
const { source } = this.props; change to const { source } = this.refs;
Related
How can I better organize my cypress code for testing so that I only need to import some functions?
I want to start by creating a file in which to authenticate on the page, and then I want to import it in a test with several functions.
I tried the following export code and it seems to have been incorrect, with errors:
export function login() {
cy.visit('https://*********')
cy.get('input[name="Parameter.UserName"]').type('*****')
cy.get('input[name="Parameter.Password"]').type('*****')
cy.contains('Login').click()
}
export default {login};
And in test :
import {login} from 'elements/pages/login.js'
Your import needs a relative URL
import {login} from '../elements/pages/login.js' // relative from cypress/integration
or if under cypress/suport/elements
import {login} from '../support/elements/pages/login.js'
Absolute imports (where path has no leading ./ or ../) are presumed to be library packages in node_modules.
Cypress provides something called the Custom commands for this purpose, you can read about it here.
Go to cypress/support/commands.js and write all your code here like:
Cypress.Commands.add('login', () => {
cy.visit('https://*********')
cy.get('input[name="Parameter.UserName"]').type('*****')
cy.get('input[name="Parameter.Password"]').type('*****')
cy.contains('Login').click()
})
And then in your any of your test, you can directly add:
cy.login()
all cys must be excuted in testing content, maybe u can try like this:
export default {
// props
visit: (url)=> { return cy.visit(url) }
get: (el)=> { return cy.get(el) }
// methods
login(){
cy.visit('https://*********')
cy.get('input[name="Parameter.UserName"]').type('*****')
cy.get('input[name="Parameter.Password"]').type('*****')
cy.contains('Login').click()
}
}
I have installed the package react-native-image picker:
npm i react-native-image-picker --save
And I have also linked it to my project:
react-native link react-native-image-picker
And when I try to import the module and use it:
import ImagePicker from 'react-native-image-picker';
ImagePicker.launchImageLibrary(options, (response) => {
// code here
}
I receive this following error:
typeError: Cannot read property 'launchImageLibrary' of undefined
What went wrong here?
You should carefully check the newest documentation of this npm package as it was migrated to newer version. The old 2.x.x version is deprecated, as written in the GitHub page of the package, thus names of key modules might have changed...
Below is the solution for it,
import {launchImageLibrary} from 'react-native-image-picker';
const changePhoto = () => {
const options = {
noData: true,
};
launchImageLibrary(options, (response) => {
console.log(response);
});
};
<TouchableOpacity onPress={changePhoto}>
<Text>Change Photo</Text>
</TouchableOpacity>
At the place of
import ImagePicker from 'react-native-image-picker';
replace with
var ImagePicker = require('react-native-image-picker');
and run the application again.
For 3.x version, you can directly import the function like
import {launchImageLibrary} from 'react-native-image-picker';
In an Expo project, I still got the same error, like this issue (since lauchImageLibrary comes from NativeModules.ImagePickerManager). But it works fine in the project initialized with React Native CLI.
For version 3.x, let run npx pod-install then get the function by that way import { launchImageLibrary } from 'react-native-image-picker';
I've got a file called "globalHelper.js" like this:
exports.myMethod = (data) => {
// method here
}
exports.myOtherMethod = () => { ... }
and so on...
I import my Helper in other files like this:
import helper from "../Helper/globalHelper";
Now there is the problem:
In the past, everything worked with that when running my build-script:
"build": "GENERATE_SOURCEMAP=false react-scripts build"
but for some reason, when I run "npm run build", I get the error:
Attempted import error: '../Helper/globalHelper' does not contain a default export (imported as 'helper')
However, when I simply start my development server (npm start), everything works just fine.
I already tried to import like import { helper } from "../Helper/globalHelper";, but that did not work either.
Does someone know how to solve that?
try exporting like this with ES6 syntax
export const myOtherMethod = () => { ... }
then
import { myOtherMethod } from '...your file'
The method you are using exports.functionName is CJS. you need to use require to get the methods.
The CommonJS (CJS) format is used in Node.js and uses require and
module.exports to define dependencies and modules. The npm ecosystem
is built upon this format.
If you want to use module method you can do this.
export { myOtherMethod1, myOtherMethod2 }
then you import like this.
import * as Module from '....file name'
Since you've not export default you should import the function with {} like :
import {helper} from "../Helper/globalHelper";
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>
);
}
}
Try add jQuery to your project, like
npm i jquery --save
or if you use bower
bower i jquery --save
then
import $ from 'jquery';
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'
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
});
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';
Just a note: if you use arrow functions you don't need the const that = this part.
It might look like this:
fetch('http://jsonplaceholder.typicode.com/posts')
.then((response) => { return response.json(); })
.then((myJson) => {
this.setState({data: myJson}); // for example
});
Add "ref" to h1 tag :
<h1 ref="source">Hey there.</h1>
and
const { source } = this.props; change to const { source } = this.refs;
I have a minimum test react app with following component:
import React from 'react';
import $ from 'jquery';
export default class App extends React.Component {
componentDidMount() {
console.log('componentDidMount', $('#helloDiv').length);
}
render() {
return <div id='helloDiv'>
Hello React!
</div>;
}
}
this works fine when loading it in browser (Chrome). The console.log() in componentDidMount() prints out 1 helloDiv element found
However, if I run the test using mocha + enzyme + jsdom, the same console.log() in App component prints out 0:
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import App from '../src/client/app/first'
describe('first test', () => {
it('should pass', () => {
const app = mount(<App />);
expect(app.find('#helloDiv').length).to.eq(1);
});
});
Note: I don't have problem with this unit test, it's passing. The real problem is when < App /> is mounted using enzyme, componentDidMount() is called but the console.log() statement inside it prints out 0, instead of 1
Here is how I run mocha:
mocha --require enzyme/withDom --compilers js:babel-core/register test/index.test.js
Any idea why jquery selector doesn't find anything in the test? It should not be mocha issue because the same issue happens if I change to jest
Finally found the issue:
Enzyme mount(<SomeComponent />) by default will do full DOM rendering but not insert the rendered component into current document (JSDom). That's why jQuery cannot find any element in current document
To do full DOM rendering AND attach to current document:
mount(<SomeComponent />, { attachTo: document.getElementById('app') });
Where app is empty div available when jsdom is setup:
global.document = jsdom('<html><head></head><body><div id="app" /></body></html>');
There needs to be some setup done before you could jsdom with jquery in node-env.
Try this if it helps.
Create a test helper file like this -
test_helper.js
import _$ from 'jquery';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
export {expect};
While running -
mocha --require enzyme/withDom --compilers js:babel-core/register --require test/test_helper.js test/index.test.js
or another way use jsdom-global without test_helper.js file.
npm install --save-dev jsdom-global
Then :
import 'jsdom-global/register';
//at the top of file , even , before importing react
I couldn't get Phuong Nguyen's answer to work. I did find the relevant page in the enzyme docs. I ended up with something like, based on the final example on that page:
const div = global.document.createElement('div');
global.document.body.appendChild(graphDiv);
const wrapper = mount(<SomeComponent />, { attachTo: div }); // same as the other answer
// clean up after ourselves
wrapper.detach();
global.document.body.removeChild(div);