How babel and JSX related or differ? - babeljs

I am learning on React JS and I have got information on JSX and babel. But I am not getting clarity on how these are helping React and how these or differ from each other

React JS
while building an app using React, you can create the components/views in two ways
using standard React object and methods
using JSX
JSX
JSX is a separate technology from React and completely optional while building React application, however it makes life much easier when you combine JSX with React.
Let's see how :
Approach 1 : standard React way
(function() {
var element = React.DOM.div({}, "Hello World");
ReactDOM.render(element, document.getElementById("app"));
})();
The above code can be found at this link.
Here, you just need to include the react and react-dom library to your page.
Nothing else is required. No JSX, no Babel.
Approach 2 : JSX way
(function() {
var HelloWorld = React.createClass({
render : function() {
return (
<div> Hello World </div>
);
}
});
var element = React.createElement(HelloWorld, {});
ReactDOM.render(element, document.getElementById("app"));
})();
The above code can be found at this link.
Note the difference here: <div> Hello World </div> is used inside JavaScript. This is called JSX syntax.
Now, compare the JSX approach with the vanilla JavaScript approach:
With JSX, You can add many more HTML like elements inline, just like standard HTML, to create the view layer.
Without JSX, the code can get messy because of the multiple layers of elements required to create HTML in JavaScript.
Babel
Now the question is, who understands JSX?.
Here We need a transpiler that understands JSX and converts it to a format that can run on browser. Babel does just this job.
Transpiling
Transpiling can be done two ways
Browser based/client side transpiling (use only for development
purpose)
include this file as a script tag
use type="text/babel" on your script tag which loads your JSX
Here's the sample code
Server based transpiling - e.g. Babel
You can use different tools like webpack etc.
Here's some sample code.
Hope this helps.

tl;dr;
JSX is an easy syntax to represent markup in your code, which Babel converts to pure JavaScript.
Long version:
JSX is a syntactical convention which aims to make element structure definition easier in a React Component's code. This XHTML-like syntax which you write inside your components gets converted into JavaScript (not very different from Hyperscript) by Babel.
A very simple Hello World component written in JSX:
class HelloWorld extends Component{
render(){
return <div><h1>Hello World!</h1></div>
}
}
And the equivalent in pure JavaScript:
class HelloWorld extends Component{
render(){
return React.createElement(
"div",
null,
React.createElement(
"h1",
null,
"Hello World!"
)
);
}
}
Do note that the above example is abbreviated to keep the focus on the JSX part.
You would soon learn that Babel actually lends a lot more power to the React world than mere JSX transpilation. It allows you to use a lot of cool new ES6/7 features right now.

Related

How to perform DOM manipulation using pyscript

I understand that pyscript can be used as a client side scripting language.
Is there a way to interact with the DOM by using CSS selectors, such as we have in javascript.
Something like :
nav_bar = get_element(".nav-bar")
Yes, you can call JavaScript functions and access globals from Python. Import the js namespace:
import js
or
from js import document
Then you can call functions like this:
<body>
<div id="msg">Loading page ...</div>
<py-script>
from js import document
msg = document.getElementById("msg")
msg.innerHTML = 'Hello world'
</pyscript>
</body>
The function get_element() is not a standard JavaScript function. It is a function located in libraries such as Telerik. Normally you can call those functions from Python provided they are not doing something special with namespaces and the library is loaded before PyScript. You can use normal JavaScript functions from Python to set CSS styles such as:
document.getElementById("msg").style.color = "blue"

Vuejs class component fields undefined

https://jsfiddle.net/78mLj9vb/
class App extends Vue {
message = 'Hello!';
shrek;//属性 property
constructor(){
super();
this.shrek = "This is my swamp!";//代入-assignment
//"This is my swamp!"がコンソールで出力されている Prints as it should
console.log(this.shrek);
this.print();
}
print(){
console.log(this.shrek);//[undefined]が出力されている Undefined printed to console
}
}
I'm learning Vuejs with class components and typescript. I do not understand why I can't access the fields of my class within methods. They are always undefined. I have tried doing the initial assignment to the field inline along with the property declaration, and I have also tried doing the assignment in the constructor. I imagine it's the Vuejs data binding mangling the class fields in a way that I do not understand, I have tried accessing them through this.$data to no avail. I understand it's probably not good design to have data that is unrelated to presentation in a component class, but this time around I don't have a database so I'm trying to hard code some data into a class method to fake it, so that I can then loop over the data w/v-for to create a select list. I've included a fiddle that looks nothing like what I'm actually trying to do, but illustrates the "issue" (my lack of understanding really).
How do you declare normal class fields outside of the Vuejs data-binding magic, or alternatively, how do you access the data that has been bound and changed by Vue?
For the best use change you code to this:
//...
#Component({
template: `
<div>
<h1>{{ message }}</h1>
<h1>{{ shrek }}</h1>
</div>
`
})
class App extends Vue {
data(){
return {
shrek: 'test',
message: 'Hello world!'
};
}
created(){
this.shrek = "This is my swamp!";
console.log(this.shrek);
this.print();
}
print(){
console.log(this.shrek);
}
}
new Vue({
el: '#app',
render: h => h(App)
})
//...
On your link here
After having practiced using Vue for a few more weeks and researching various topics on the internet I have come to the conclusion (which should have been obvious to me at first) that the answer is to use components only for what components are good for. That is to say, if you have some logic that gets gnarly and you want to alleviate it with helper functions, those helper functions can be declared outside the class as regular functions and used within the component code. Another upside of this approach is that if multiple components would get use out of your helper function or initialization code, you can instead move it into a typescript or javascript module and import it into those components that need it.
データ初期化や普通の論理を実施するヘルパー関数をコンポーネント内に置くより別の標準なTypescriptやJavascript関数に置いた方が良さそうです。Vuejsのコンポーネント・クラスの良い点はview作りだけでviewと関係ない論理をコンポーネント以外に置くべきです。それにそうするとその論理を別のファイルに置いてモジュール形で複数のコンポーネントはその論理を使えるようになります。

How to import .html fragment using es6 syntax in TypeScript

How to import an HTML template from a relative path like this:
import customSelectHtml from "./custom-select.html!text";
TypeScript compiler complains that it cannot find module. I was trying to create an ambient module definition, but it doesn't allow relative paths in module names. I am using SystemJS as a module loader.
I'm not using typescript, but I do use ES6. Might be useful for you.
The way that I solve this is by declaring template strings using ` ` quotes. It works fine for me, I would be happy to know if someone thinks this is a bad habbit.
below a snippet with Angular(-ui-router).
index.js
var indexTemplate = `
<div>
<h1>{{ Index page }}</h1>
</div
`
export {indexTemplate}
config.js
import { indexTemplate } from './index.js'
function config($stateProvider){
$stateProvider.state('index', {
url: '/',
controller: 'indexController',
template: indexTemplate
})
}
For completeness, this assumes indexController is defined elsewhere. Also, this config function is exported to a place where app is defined. But that all is not related to the question.
It is impossible.
Due to the definition of what is module in typescript, and as far as I know in ES6 javascript (import). Module cannot be html. The common approach is to import a javascript module that exports a string containing html, css, whatever. But that is not importing of the file with raw html.
Maybe you want to have a look at html imports also, but that is completely different thing.
You can import it using require syntax
1) Create app.d.ts file and require definition so typescript know this is function. (you don;t need to add any addition library, systemJs support require syntax)
declare function require(params:string): any;
2) Now you can import your html using
var template = require('./custom-select.html!text')
I found it even better because you can use require inline
var directive = {
template: require('./custom-select.html!text'),
scope: {}
}
I don't know about SystemJS, but this is definitely possible with Webpack and the html-loader

Dynamic HTML with Foundation and React

I'm trying to use Foundation with React, but I'm experiencing some problems regarding dynamic creation of interactive content.
Here is some coffee script code which shall create a data-dropdown but I think the problem is more general so that it's independent of the code.
render : ->
a href : '#', "data-dropdown" : 'drop',
'Dropdown link text'
div id : "drop", "data-dropdown-content" : true, className : "f-dropdown content",
p 'Dropdown content text'
Normally, one could call the Foundation function on dynamically created HTML nodes, but I don't think that this harmonizes with the spirit of React.
Is there a best practice for this case? Or should I switch to React-Bootstrap?
I also tried to invoke the foundation method on the DOM nodes, but beside the fact that it doesn't work, it would be plain ugly.
You're probably not going to want to use foundation or bootstrap javascript in your reactjs code. It usually doesn't work at all. Moving to react-bootstrap like you have is probably the way to go,
http://react-bootstrap.github.io/
Here's a pretty awesome react resource to help find other react components if you need something specific,
http://react-components.com/

Getting the emberjs starter-kit to work with coffeescript

i'm trying to get the starter-kit example of ember.js to work directly with an app written in coffeescript (with the use of http://coffeescript.org/extras/coffee-script.js).
I want to use this in an development environment, without the need to convert the coffescript to javascript first (manually or with tools like jitter).
Basically i just replaced the line
<script src="js/app.js"></script>
with the lines
<script src="js/libs/coffee-script-1.3.3.min.js"></script>
<script type="text/coffeescript" src="coffee/app.coffee"></script>
in the index.html
All changes i've made can be found in my fork on github at https://github.com/GordonSchmidt/starter-kit
The coffescript itself seems to be fine, because when i convert it to javascript first the starter-kit application works with this javascript. But when i use the coffeescript directly it throws the error "assertion failed: Unable to find view at path 'App.MyView'" in line 45 of ember-0.9.8.1.js. The coffee-script.js all by itself seems to work as well (see demo.html). So it has to be a conflict between ember.js and coffee-script.js.
But I'm not able to find this error. Can someone please point me in the right direction?
from coffeescript.org
The usual caveats about CoffeeScript apply — your inline scripts will
run within a closure wrapper, so if you want to expose global
variables or functions, attach them to the window object.
your coffeescript should look something like this:
<script type="text/coffeescript">
window.App = App = Em.Application.create()
App.MyView = Em.View.extend(
mouseDown: -> window.alert "hello world!"
)​
</script>
see here for a fiddle