How to use jsx in preact via cdn? - preact

got this code from preact's site, and try to make it work without babel building process, but failed, anybody knows if this is possible? Thanks,
http://jsfiddle.net/e281k4wz/117/
'use strict';
const { Component, h, render } = window.preact;
render((
<div id="foo">
<span>Hello, world!</span>
<button onClick={ e => alert("hi!") }>Click Me</button>
</div>
), document.body);

Yes. You have to include babel before your jsx code and use the script as type="text/babel" see the following example with react
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class App extends React.Component {
render() {
return (
<div className="app-content">
<h1>Hello from React</h1>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
</body>
</html>

You cannot directly use the JSX into the JavaScript as it's a invalid syntax.
For running the preact into the client you have to either transpile the jsx code into valid javascript or use the helper method (Component , h , render) provided by preact.
HTML
<h1>Render by Preact client library using h and render function</h1>
<div id="preact">
</div>
JavaScript
var Component = window.preact.Component,
h = window.preact.h,
render = window.preact.render;
var PreactApp = function (props){
return h('h1',
{className: ''},
'Hello from Preact world!');
}
render(PreactApp(),document.getElementById("preact"));
Here in JS if you see h ( converting jsx to vdom ) and render (converting vdom to html ) function actually do the magic. Read more about from the official documentation - https://preactjs.com/guide/api-reference
Working example - https://jsfiddle.net/97125m3z/2/

Technically it is possible by using the HTM package, as long as you're targeting recent browsers that understand template strings. See https://github.com/developit/htm for details.
However, this will render slower than simply creating the components using h() as it is a whole heap of string parsing. It also makes it difficult to use syntax highlighting in your IDE, which makes debugging frustrating.
I used HTM when I was first getting used to using Preact without a build step, but very quickly replaced it with manually creating the components and eliminated the JSX.
You get a better understanding of how everything fits together if you don't use the JSX abstraction. Babel compiles it down into createElement calls anyway.

Related

How to render the HTML into react component

I want to render the pure HTML coming from some external source into react component. I saw few solutions where people are talking about some conversion tools (HTML to JSX) but I want to handle everything in my component so while mounting it will get the HTML response and that needs to render.
You can use dangerouslySetInnerHTML for this:
function createMarkup() { return {__html: 'First ยท Second'}; };
<div dangerouslySetInnerHTML={createMarkup()} />
But as the method name suggests: you should be very sure of what you are doing there and the security implications it has.
This shouldn't be difficult to do . Assign your HTML to a div and then render it using {variable name} JSX allows you to do this and with ES6 integration you can also use class instead of className.
var Hello = React.createClass({
render: function() {
var htmlDiv = <div>How are you</div>
return <div>Hello {this.props.name}
{htmlDiv}
</div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>

Using express handlebars with vue js

I am building an app using express handlebars for server-side templating. On the client side, I want to use vue.js. However, they both share the same double brace notation {{ variable }}. Right now, my vue.js variables are not showing because my handlebars template is overriding it. For example:
home.html:
<div id="app">
{{message}} //this will not show up
</div>
home.js:
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
});
HOWEVER, if I define message in my server side controller:
res.render('../views/home', {
message: 'message from handlebars'
});
the message will show up.
So in summary, is there a way i can use vue.js for client side templating while still using express-handlebars for server side templating?
Thanks in advance!
This can be solved by escaping the first brace in your handlebars template.
<div id="app">
\{{message}} //this will not be replaced by handlebars
</div>
You can change the Vue demlimiters to something else, e.g.:
Vue.config.delimiters = ['${', '}']
You can "escape" the Vue delimiters in Handlebars by using a raw block helper:
Handlebars.registerHelper('vue-js', function(options) {
return options.fn();
});
Usage in the Handlebars template:
{{{{vue-js}}}}
<div id="app">
{{message}}
</div>
{{{{/vue-js}}}}

meteor with flow router layout is rendered twice

I don't know why but my layout is rendered two times.
Here is my index.html:
<head>
<title>title</title>
</head>
<body>
{{>layout}}
</body>
Here is my layout:
<template name="layout">
{{#if canShow}}
{{>Template.dynamic template=content}}
{{else}}
{{> loginButtons}}
{{/if}}
</template>
So here without route my template is display just one time.
Here is my route:
FlowRouter.route('/', {
action() {
BlazeLayout.render("layout", {
content: "home"
});
}
});
But with this route my template is display a second time.
This is my helpers, I think there is nothing to do with this problem but we never know.
Template.home.onCreated(function() {
this.autorun(() => {
this.subscribe('post');
});
});
Template.layout.helpers({
canShow() {
return !!Meteor.user();
}
});
Template.home.helpers({
cats() {
return Posts.find({});
}
});
you don't need to render layout in the body.
The router will take care of the rendering.
so, just have
<body>
</body>
or don't even have it at all.
Edit: Thanks to Keith, I have a better understanding of my problem. Here is his comment:
one thing to keep in mind, all the html you write in meteor isn't kept as html. It all gets converted to javascript. Things like index.html do not get pushed to the browsesr. Meteor just takes all the html you write converts it to javascript and renders what it needs to based on what your code says. This is how it knows todynamically change and rerender html
For things like changing title of the head or add meta etc, we can do it directely in the javascript.
ex: Meteor - Setting the document title

Node WebKit: File Dialog select directory path

I am trying to add a folder selector to my node webkit app. Looking at the docs I can just use:
<input type="file" nwdirectory />
But these still seems to return the number of files, which it is not supposed to do.
here is the test code,
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<input type="file" id="fileDialog" nwdirectory />
<script>
function chooseFile(name) {
var chooser = $(name);
chooser.change(function(evt) {
console.log($(this).val());
});
chooser.trigger('click');
}
chooseFile('#fileDialog');
</script>
</body>
</html>
How can I get just the folder path as I will then use this with the fs module
Thanks
EDIT: This looks like a regression issue in v0.12.0 Alpha as it appears to work fine in v0.11.5.
Hope this is helpful for you.

How to write a lodash template loader for requirejs

I'm using a requirejs plugin to define "tmpl!" loader (not a jquery template, but a lodash template. The problem is that the text! loader is adding a ";" at the end of the template. This is being rendered and is breaking everything.
(function(global){
"use strict";
define({
load : function(name, require, load, config) {
var deps = [];
deps.push('text!' + name);
deps.push('underscore');
require(deps, function(source, _) {
var template = _.template(source);
load(template);
});
}
});
})(this);
How can I stop text! from adding a semi-colon? Or: is there a better way to do this?
Taking the questions in reverse order:
is there a better way to do this?
It seems there is an existing implementation of this, and you might want to consider using it rather than writing your own. Although the simple case is a small amount of code, there are a bunch of r.js optimizer-related things you might eventually need.
But regarding your implementation logic, I noticed that this similar project for Handlebars does not use the text! plugin but instead does its own XHR in the load() method. This is not explained, but he gives some guidance for adapting it to other templating languages. Note: the link came from this question where there is some other good discussion of the approach.
How can I stop text! from adding a semi-colon?
I tried your plug-in and did not get any added semicolons. Perhaps you could post more of the sample project and templates? Below is mine, with everything in one flat folder for simplicity:
require.js: latest from RequireJS site
domReady.js: latest from RequireJS site
text.js: latest from RequireJS site
lodash.js: latest from lodash site
tmpl.js: your example loader from the question
index.html:
<!DOCTYPE html>
<html>
<head>
<script src='require.js'></script>
<script>
requirejs.config({
map: {
'*': { 'underscore': 'lodash' }
}
});
require( [ 'underscore', 'tmpl!friend-template.htm', 'domReady!' ]
, function( _, friendTemplate ){
var friendsData = [{ name: 'Bob', age: 35 }, { name: 'Fred', age: 38 }];
document.body.innerHTML = friendTemplate( {friends: friendsData});
});
</script>
</head>
<body>
<!-- To be populated dynamically. -->
</body>
</html>
friend-template.htm:
<ul>
<% _.forEach(friends, function(friend) { %>
<li>
<span><%- friend.name %></span>
<span>( Age: <span class="value"><%- friend.age %></span> )</span>
</li>
<% }); %>
</ul>
I've created a loader specifically for Lo-Dash which you can see here:
https://gist.github.com/tbranyen/6821045
Note: I have no unit tests or assurances this free of bugs, but from my initial testing it appears to work fantastic.
This is better in a number of ways than requirejs-tpl which bakes in it's own implementation which is not exposed. It also requires a file extension and hardcoded path. Both of these are configurable in my code.
Edit: I've since released a project called lodash-template-loader which has tests. https://github.com/tbranyen/lodash-template-loader

Resources