React and JQuery plugin ( $ is not defined) [duplicate] - javascript

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

Cypress - import and export functions

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()
}
}

react-native-image-picker is undefined

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';

react helper import fails in production but works in development

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";

How do you import a javascript package from a cdn/script tag in React?

I'd like to import this javascript package in React
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
However, there is no NPM package, so I can't import it as such:
import dwolla from 'dwolla'
or
import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'
so whenver I try
dwolla.configure(...)
I get an error saying that dwolla is undefined. How do I solve this?
Thanks
Go to the index.html file and import the script
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
Then, in the file where dwolla is being imported, set it to a variable
const dwolla = window.dwolla;
This question is getting older, but I found a nice way to approach this using the react-helmet library which I feel is more idiomatic to the way React works. I used it today to solve a problem similar to your Dwolla question:
import React from "react";
import Helmet from "react-helmet";
export class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myExternalLib: null
};
this.handleScriptInject = this.handleScriptInject.bind(this);
}
handleScriptInject({ scriptTags }) {
if (scriptTags) {
const scriptTag = scriptTags[0];
scriptTag.onload = () => {
// I don't really like referencing window.
console.log(`myExternalLib loaded!`, window.myExternalLib);
this.setState({
myExternalLib: window.myExternalLib
});
};
}
}
render() {
return (<div>
{/* Load the myExternalLib.js library. */}
<Helmet
script={[{ src: "https://someexternaldomain.com/myExternalLib.js" }]}
// Helmet doesn't support `onload` in script objects so we have to hack in our own
onChangeClientState={(newState, addedTags) => this.handleScriptInject(addedTags)}
/>
<div>
{this.state.myExternalLib !== null
? "We can display any UI/whatever depending on myExternalLib without worrying about null references and race conditions."
: "myExternalLib is loading..."}
</div>
</div>);
}
}
The use of this.state means that React will automatically be watching the value of myExternalLib and update the DOM appropriately.
Credit: https://github.com/nfl/react-helmet/issues/146#issuecomment-271552211
for typescript developers
const newWindowObject = window as any; // cast it with any type
let pushNotification = newWindowObject.OneSignal; // now OneSignal object will be accessible in typescript without error
You can't require or import modules from a URL.
ES6: import module from URL
What you can do is make an HTTP request to get the script content & execute it, as in the answer for how to require from URL in Node.js
But this would be a bad solution since your code compilation would depend on an external HTTP call.
A good solution would be to download the file into your codebase and import it from there.
You could commit the file to git if the file doesn't change much & are allowed to do it. Otherwise, a build step could download the file.
var _loaded = {};
function addScript(url) {
if (!loaded[url]) {
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);
_loaded[url] = true;
}
}
how to load javascript file from cdn server in a component
Add the script tag in your index.html and if you are using Webpack, you can use this webpack plugin https://webpack.js.org/plugins/provide-plugin/

Jquery in React is not defined

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;

Categories

Resources