JavaScript ReferenceError: $ is not defined - javascript

I have an html file that looks like this:
<!DOCTYPE html>
<html>
<head>
<title>AppName</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="container"></div>
<script src="/bundle.js"></script>
</body>
</html>
And I have a javascript file that contains this:
EDIT: included jQuery via npm, and it seems to have worked.
export function getData(arg, callback) {
var $ = require('jQuery'); // This line was added via EDIT above.
$.ajax({
type: "GET",
url: "/get_data",
data: {data: arg},
success: callback
});
}
When I go to my page and execute the function, I eventually get this error:
Uncaught ReferenceError: $ is not defined
at Object.getData (http://localhost:1234/static/bundle.js:21665:6)
Based on the questions/answers I've seen on SOF, it seems like the solution was to include the jquery script in my html file.
Any ideas what I might be doing wrong?
EDIT: As per request, here is my react index.js file. The error is coming from within the searchApi.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/SearchBar';
import * as searchApi from './api/searchApi';
class App extends React.Component {
constructor() {
super();
this.getData = this.getData.bind(this);
this.processData = this.processData.bind(this);
}
getData(data) {
searchApi.getData(data, this.processData);
}
processData(payload) {
console.log(payload);
}
render() {
return (
<div>
<SearchBar getData={this.getData}/>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);

Related

react-json-schema tutorial does not show up in browser

I am completely new to web development (html/js) but would now like to use the react-json-schema package which works great in the provided sandbox.
However, I can't even get the tutorial to work. I have written an html, as given in the tutorial:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<script type="text/jsx" src="react.js"></script>
</body>
</html>
the corresponding javascript file "react.js":
const Form = JSONSchemaForm.default;
const schema = {
title: "Test form",
type: "string"
};
ReactDOM.render((
<Form schema={schema} />
), document.getElementById("app"));
However, the schema simply does not show up in a browser when opening the html. There is no error message.
Things I have tried:
1.) importing the scripts from the cdn, so adding these lines in the html head:
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/#rjsf/core/dist/react-jsonschema-form.js"></script>
2.) re-installing npm and the react-json-schema, react and react-dom packages both locally and globally
3.) importing said packages in the js:
import react from React
import import ReactDOM from 'react-dom'
import Form from "#rjsf/core";
try below:
import Form from 'react-jsonschema-form';
class Index extends DataComponent{
constructor(props){
super(props);
this.state={
schema: {
type: 'object',
title: 'Info',
properties: {
task: {
type: 'string',
title: 'First Name'
}
}
}
}
}
render(){
return(
<Form
schema={this.state.schema}
/>
)
}
}
If you have installed the library then remove
//const Form = JSONSchemaForm.default;

jQuery plugin not accessible in React

I have not been successful in importing the following jQuery plugin into my React app:
http://bililite.com/inc/jquery.parsecss.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://bililite.com/inc/jquery.parsecss.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
My React component:
import React, { Component } from "react";
class Main extends Component {
constructor(props) {
super(props);
$.parsecss(".mybutton { color: #ff0000; }", function(css) {
var x = 0;
x++;
});
}
}
The jQuery function parsecss is undefined.
Adding it to my index.html using a script tag did not work. Only when adding it as a node module and importing it, did it work. Of course, many jquery plugins are not available using npm, so I had to create my own package. This was actually quite simple. In my node_modules folder I created a folder called parsecss and a sub folder called dist. In dist I placed the jquery plugin. In the parsecss folder I added a package.json file that had the following content:
{
"main": "dist/jquery.parsecss.js",
"name": "parsecss",
"title": "parsecss"
}
You need to add jQuery as I showed in my sample code above in the index.html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
And in the React component:
/* global $ */
import React, { Component } from "react";
import parsecss from 'parsecss'
class Main extends Component {
constructor() {
$.parsecss(".mybutton { color: #ff0000; }", function(css) {
var x = 0;
x++;
});
}
}
Note: The comment /* global $ */ fixes a console error that indicates that $ is not defined.

How to create and render a React Component after babelify/transpiling?

I have a hello world react component that is written in JSX, transpiled with babel, and then included in the hello.html template of a Flask app. What I have working is creating and rendering the component before transpiling as such:
const hello = <Hello name="world" />;
ReactDOM.render(hello, document.getElementById('hello'));
How can I do those two steps in a <script> tag in my hello.html template? My goal is to be able to pass that name variable from the template to the component and then render it.
A little more context:
The JSX hello.js looks like this:
import React from 'react';
import ReactDOM from 'react-dom'
import { render } from 'react-dom'
class Hello extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>Hello {this.props.name}!!!</div>
)
}
}
//The following works:
//const hello = <Hello name="world" />;
//ReactDOM.render(hello, document.getElementById('hello'));
hello.html looks like this:
<html>
<head>
</head>
<body>
<div>ASDF</div>
<div id="hello"></div>
</body>
{# The following line is a post babelify (transpiled) hello.js #}
<script type="text/javascript" src="{{ url_for('static', filename='js/hello.js') }}"></script>
<script type="text/javascript">
{#
What goes here? The code in the above section does not work.
The transpiled code defines a "var Hello = /*#__PURE__*/ function (_React$Component) { ...".
const hello = Hello(); does not throw an error, but also does not render or pass an argument.
hello.render(); is also something that I have tried, along with arguments for div/id to render in and name.
#}
</script>
</html>
Correction: Calling Hello() does not throw an error if the script is text/babel, in which case the script probably isn't doing anything.
The Flask route looks like this:
#app.route(u'/')
def index():
return render_template(u'hello.html', name="universe")
Two ways you can pass variables from your server application to react component:
Use the html data-variable prop.
Create a global variable. Something like window.variable
Then you should be able to access variable as a props like props.variable in your react-component.
My recommended approach I would take is to use a bundler such as SystemJS (version 2), and you will have something like the following:
<!DOCTYPE html>
<html>
<head>
<script src="node_modules/core-js-bundle/minified.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script type="systemjs-importmap" src="systemjs.imports.json"></script>
<script src="node_modules/systemjs/dist/system.min.js"></script>
<script src="node_modules/systemjs/dist/extras/named-exports.min.js"></script>
<script>
System.import('../.playground/index.js').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<div>ASDF</div>
<div id="hello"></div>
</body>
</html>
And index.js will look something like this
ReactDOM.render(
(< Hello/>),
document.getElementById('app')
);
Then your systemjs-importmap will look like this
{
"imports": {
"react": "../node_modules/react/umd/react.production.min.js",
"react-dom": "../node_modules/react-dom/umd/react-dom.production.min.js",
// ... other named exports you want to add like the Hello component here
}
}

Why do I need import React statement even if I don't use React explicitly?

I have an React App, following is JavaScript code
import React from 'react';
import ReactDOM from 'react-dom';
const App = function(){
return <div>Hi</div>
}
ReactDOM.render(<App />, document.querySelector('.container'));
And the HTML file is as following.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style/style.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAq06l5RUVfib62IYRQacLc-KAy0XIWAVs"></script>
</head>
<body>
<div class="container"></div>
</body>
<script src="/bundle.js"></script>
</html>
The question I don't understand is that if I remove import React from 'react', it will show error message like below.
Uncaught ReferenceError: React is not defined
But I don't use React in my code explicitly anywhere, why would it show a message like this. Can anyone tell me what's going on under the hood?
UPDATE:
Not exactly the same question with this one, since what I have in my code is just an individual component, not involving any parent component.
Using JSX (<App />) is just a syntatic sugar for React.createElement().
So when your code is transpiled to pure javascript, references to React will appear there, so you need the import for that.
So yes, you're using it, although you don't see it
See what is your code transpiled to here
'use strict';
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var App = function App() {
return React.createElement(
'div',
null,
'Hi'
);
};
_reactDom2.default.render(React.createElement(App, null), document.querySelector('.container'));

Using globally defined script inside the component

I am using global script declaration inside index.html
<!DOCTYPE html>
<html>
<head>
<script src='https://js.espago.com/espago-1.1.js' type='text/javascript'></script>
...
</head>
<body>
...
</body>
Now I want to use it inside the component.
import * as React from "react";
import * as $ from "jquery";
//how to import Espago?
export default class EspagoPayment extends React.Component<any, any> {
componentDidMount() {
$("#espago_form").submit(function(event){
var espago = new Espago({public_key: 'xxx', custom: true, live: false, api_version: '3'});
espago.create_token({
...
});
});
}
render() {
return (
...
);
}
}
Webpack gives an error on build.
error TS2304: Cannot find name 'Espago'
How to get Espago visible inside the component?
Maybe there is other way to link to online js resource?
You have to tell TypeScript that it's defined somewhere else.
declare var Espago: any;
See https://stackoverflow.com/a/13252853/227299

Categories