Component undefined in ReactJS - javascript

I'm playing around with ReactJS. I have defined three components, which are nested:
UserProfile.jsx
var React = require('react');
var UserProfile = React.createClass({
getInitialState: function() {
return {
username: "zuck"
};
},
render: function() {
return (
<UserProfile>
<ProfileImage username={this.props.username}/>
<ProfileLink username={this.props.username}/>
</UserProfile>
);
}
});
React.render(<UserProfile username="zuck"/>, document.body);
module.exports = UserProfile;
ProfileLink.jsx
var React = require('react');
var ProfileLink = React.createClass({
render: function() {
return (
{this.props.username}
);
}
});
module.exports = ProfileLink;
ProfileImage.jsx
var React = require('react');
var ProfileImage = React.createClass({
render: function() {
return (
<img src="//graph.facebook.com/{this.props.username}/picture"/>
);
}
});
module.exports = ProfileImage;
My html file basically only includes the three jsx files (btw, is there a way to bundle all these into a single request during development?)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React FB Link</title>
</head>
<body>
<script type="text/javascript" src="UserProfile.jsx"></script>
<script type="text/javascript" src="ProfileLink.jsx"></script>
<script type="text/javascript" src="ProfileImage.jsx"></script>
</body>
</html>
I'm using beefy to handle and serve the JSX files, using beefy *.jsx 8000 -- -t reactify.
The resulting files are (in truncated form):
UserProfile.jsx
ProfileLink.jsx
ProfileImage.jsx
Loading the html page results in an error:
Uncaught ReferenceError: ProfileImage is not defined
with reference to line 15 in UserProfile.jsx:
React.createElement(ProfileImage, {username: this.props.username}),

You might need to load ProfileImage.jsx and ProfileLink.jsx before your UserProfile.jsx since right now the page is parsing Userprofile.jsx first and it doesn't know what ProfileImage mean (because you haven't loaded it yet)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React FB Link</title>
</head>
<body>
<script type="text/javascript" src="ProfileLink.jsx"></script>
<script type="text/javascript" src="ProfileImage.jsx"></script>
<script type="text/javascript" src="UserProfile.jsx"></script>
</body>
</html>
You can use any module bundler to bundle up your files (Browserify, Gulp, Webpack) into one single file as entry point

Related

Access to javascript module Class/object from index.html

I defined Class in my javascript file...I imported that file into html page:
<script type="module" src="./js/controller.js"></script>
How can I now acces to classes inside of that js file?
I want to have something like this (in my html file):
<script>
let app = null;
document.addEventListener('DOMContentLoaded', function () {
//Init app on DOM load
app = new MyApp();
});
</script>
But it doesn't work (I get Uncaught ReferenceError: MyApp is not defined)...If I include this DOMContentLoaded listener into end of my controller.js file, It works. But I lost reference to app variable this way (which I don't want)... Is there way to have reference to something defined in modules?
Most important reason why I want to have that reference is ability to access to my app object from google chrome console...
Thanks!
You can access your class in js file from html in the following way-
My Home.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script type="module">
import { Car } from "./main.js";
let obj= null;
alert("Working! ");
obj = new Car("Mini", 2001);
obj.PrintDetails();
document.addEventListener('DOMContentLoaded', function () {
let obj2 = new Car("Merc", 2010);
obj2.PrintDetails();
});
</script>
</head>
<body>
<h1> Lets try something <br></h1>
</body>
</html>
My main.js file:
export class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
PrintDetails() {
console.log(" Name = "+ this.name);
console.log(" year = "+ this.year);
}
}

Localhost not loading module

I am using modern Javascript MyClass.js
export default class MyClass {
constructor(x) {
this.val=x? x: "Hello!"
console.log("MyClass:",x)
}
}
at my http://localhost/myfolder/mypage.htm, with the source below,
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
<script type="module" src="./MyClass.js"></script>
<script>
'use strict';
document.addEventListener('DOMContentLoaded', function(){
alert(123)
let x = new MyClass(11);
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
Why console say "Uncaught ReferenceError: MyClass is not defined"?
PS: this question is a complement for this other about using ES6+ with browser+NodeJs.
NOTE: using UBUNTU ith Apache's Localhost... Some problem with myfolder a symbolic link to real folder? at /var/www/html I used ln -s /home/user/myRealFolder/site myfolder
you need to import the module before using it
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script type="module" src="./MyClass.js"></script>
<script type="module" id="m1">
// script module is an "island", not need onload.
'use strict';
import MyClass from './MyClass.js';
let x = new MyClass(11); // we can use here...
console.log("debug m1:", x) // working fine!
window.MyClassRef = MyClass; // "globalizing" class
window.xRef = x // "globalizing" instance
</script>
<script> // NON-module global script
document.addEventListener('DOMContentLoaded',function(){
// only works after all modules loaded:
console.log("debug:", window.xRef) // working fine!
let x = new window.MyClassRef(22); // using class also here,
console.log("debug:", x) // working fine!
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
There are two ways to use an imported class:
at module scope (script m1): you can use new MyClass(), and can "globalize" instances (e.g. xRef) or the costructor's class (MyClassRef).
at global scope: to work together other libraries or with main script, use a global reference, e.g. new window.MyClassRef().
All this solution relies upon "static import"...
Optional dynamic import
You can use also import with ordinary default <script> (no type="module"), and no "onload", using this solution, instead the last script:
<script>
'use strict';
import('./MyClass.js').then(({default: MyClass}) => {
alert(123) // async block
let x = new MyClass(11);
});
</script>
See dynamic import.

How to access client window javascript global variable with Spectron

I'm trying test of Electron app with Spectron.
But I can't test client window javascript global variable.
Here is my simplified code.
Please help me.
Thanks.
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MY ELECTRON</title>
<script type="text/javascript" src="script.js"></script>
<link href="./style.css" rel="stylesheet">
</head>
<body>
</body>
</html>
script.js
let mode;
function onload_func(){
mode = 'normal';
}
window.onload = onload_func;
spec.js
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')
let app;
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
app = new Application({
path: electronPath,
args: [path.join(__dirname, '../src')]
})
return app.start()
})
afterEach(function () {
if (app && app.isRunning()) {
return app.stop()
}
})
it('initial mode',function(){
assert.equal(app.client.mode,'normal');
})
})
I'm not sure if it will solve your specific tests, but app.browserWindow should do the trick since as they say:
It provides you access to the current BrowserWindow and contains all
the APIs.
Note that it's an alias to require('electron').remote.getCurrentWindow()
Read more: https://github.com/electron/spectron#browserwindow

requirejs define a module can not get the return value

I can not get the exports value When I import external links
js file (main.js) as a dependency with requirejs,see the code.
console.log(m) //undefined
but I define the module "t" as a dependency in internal,it can get the return
value,see the code.
console.log(n) //test
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcss.com/require.js/2.3.3/require.min.js" ></script>
<script type="text/javascript">
define("t",["main"],function(m){
console.log(m) //undefined
return "test";
});
require(["t"],function(n){
console.log(n) //test
});
</script>
</body>
</html>
Here is the main.js:
define("m",[],function(){
return "test";
})
So what's the wrong with it?
Define your main.js module like this and it should work fine:
define([],function(){
return "test";
});
Your HTML will be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcss.com/require.js/2.3.3/require.min.js"></script>
<script type="text/javascript">
requirejs.config({
baseUrl: '/', // set proper base path
paths: {
"main": "...path to main js...."
}
});
define("t", ["main"], function(m) {
console.log(m)
return "test";
});
require(["t"], function(n) {
console.log(n) //test
});
</script>
</body>
</html>
Here is a working pen

Update to angular component router from original angular router gives the errors:

See the code here: http://plnkr.co/edit/xIRiq10PSYRsvNE0YWx7?p=preview.
I'm getting the following 2 errors.
Route must provide either a path or regex property
[$compile:ctreq]
http://errors.angularjs.org/1.5.3/$compile/ctreq?p0=ngOutlet&p1=ngOutlet
index.html
<!DOCTYPE html>
<html ng-app="favMoviesList">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js</script>
<script src="https://unpkg.com/#angular/router#0.2.0/angular1/angular_1_router.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<script src="module.js"></script>
<script src="movies-list-component.js"></script>
<script src="movie-rating-component.js"></script>
<script src="movie-app-component.js"></script>
</head>
<body>
<movie-app></movie-app>
</body>
</html>
module.js
(function(){
var module = angular.module("favMoviesList",["ngComponentRouter"]);
module.value("$routerRootComponent","movieApp");
module.component("appAbout",{
template:"This is about page"
});
}());
movie-app-component.js
(function(){
var module = angular.module("favMoviesList");
module.component("movieApp",{
templateUrl:"movie-app-component.html",
$routeConfig:[
{ path:"/list",component:"movieList",name:"List"},
{ path:"/about",component:"appAbout",name:"About"},
{ paht:"/**", redirectTo:["List"] }]
});
}());
You made a typo: paht should be path.
The second error is because your controller 'ngOutlet', required by directive 'ngOutlet', can't be found.

Categories