ClojureScript – Power of Clojure to the web

ClojureScript is a compiler for Clojure that targets JavaScript. It is designed to emit JavaScript code which is compatible with the advanced compilation mode of the Google Closure optimizing compiler.

Why ClojureScript?

  • Allows to use functional programming.
  • Uses Immutable data structures. (Immutable.js library is available to enable use of immutable data structures with JavaScript. Watch Christian Johansen’s talk on Immutable JavaScript)
  • Uses Google Closure Compiler : advanced code compiling with dead code elimination
  • core.async: makes ajax asynchronous call look like synchronous without the use of callbacks
  • Om/React : React provides a functional approach for rendering DOM. Using ClojureScript and React makes some tasks , for example undo quite simple

A great tutorial to follow to learn ClojureScript is http://clojure.org/clojurescript which covers the basics of ClojureScript, environment set up with the use of Leiningen project, DOM interaction, routing,AJAX call, core.async, Om/React, browser enabled REPL and more.

The difference between JavaScript and ClojureScript is described in Compare ClojureScript with JavaScript.

Below is an example how to create an object in JavaScript and ClojureScript.

Create object in JavaScript
var foo = {foo: "bar"};
Create objects in ClojureScript
;; Create JavaScript objects with `js-obj`.
(def foo (js-obj "foo" "bar"))

;; ClojureScript supports  JavaScript data literals via the `#js` reader literal.
(def foo #js {"foo" "bar"})

;; It’s important to note that `#js` is shallow, the contents of
;;`#js` will be ClojureScript data unless preceded by `#js`.
;; This is a mutable JavaScript object with an immutable
;; ClojureScript object inside.
(def foo #js {"foo" "bar"})

Since I am using LightTable as the IDE,  an introduction to clojureScript to LightTable users is useful. If you are using a Windows machine, use ctrl + enter instead of command +ENTER to evaluate each form.

I got hooked up with the use of React with ClojureScript. The following interfaces are available to integrate React

The advantages and disadvantages of each of the above interface are described in “How to use React in ClojureScript, and why”

Furthermore external JavaScript libraries can be integrated with ClojureScript with the use of :foreign-libs option.

Building Single Page App “SimpleCalculator” with Reagent, Secretary and Accountant 

I followed the figwheel tutorial to create a project based on figwheel leiningen template.

lein new figwheel SimpleCalculator

It automatically creates a directory “SimpleCalculator”.   Open the folder using Light Table. It has the following structure.

figwheelFolderStruc

Open project.clj and add the following dependencies

[reagent "0.5.1"
:exclusions [org.clojure/tools.reader]]
[reagent-forms "0.5.13"]
[reagent-utils "0.1.7"]
[secretary "1.2.3"]
[venantius/accountant "0.1.6"
:exclusions [org.clojure/tools.reader]]

The dependencies tag look like

dependencies

Reagent is the interface for React in ClojureScript. Secretary is client side router for ClojureScript. Accountant makes navigation simple by triggering dispatches to Secretary defined routers and update browser’s path without a page reload.

Open Index.html file. Add the h3 tag above the “app” div.

<h3> Welcome to calculators</h3>

The Index.html will look like

Index

Open core.cljs  and copy and paste the code.

To run the application type
lein figwheel

lein_Figwheel

From the browser navigate to http://localhost:3449

The Maths Calculator is displayed by default

Maths_Calc

Click on BMI link to load the BMI calculator

BMI_Calc

The BMI calculation code has been taken from “Reagent: Minimalistic React for ClojureScript”

Click on Pension Age link to load Pension Age calculator

StateAgeCalc

Starting with React- Factorial react Component

React is an Open Source, client-side web library for building composable user interfaces developed by Facebook and Instagram. The Instagram website, Facebook’s comment and like components are  developed with React.

React home page provides code samples that run live and give results just next to it.

React_Facebook.JPG

The getting started page provides necessary documentation and has a download link for the Starter Kit that’s a convenient package that includes HTML templates, the React libraries and this set of examples.

DownloadReactStarterKit

Advantages
– Speed: React renders user interfaces faster.
– Declarative: React is a set of components , each of which declaratively defines a mapping between some state and the desired UI. The interface is only changed by changing the state. This make it easier to prevent bugs and reason.
– Composable: React components are self-contained units of functionality. Publishes a simple interface that defines inputs as properties and their outputs as callbacks. By implementing the interface, React components can be freely nested within each other.

Hello World Component

The React.Js Component can be described as below where HTML is the output while state and properties are the inputs.

State,Properties –> var Component = React.CreateClass  –> HTML

A component can change its state but not its properties value. The component triggers a re-render event when state changes.

JsFiddle provides an interface to experiment with JavaScript code including React Library.

JsFiddle Hello World component is similar code to the one on React Homepage.

React_ExampleOfApplication.JPG

The React.createClass function is used to define components. In the example above, the “Hello” component is created and property “name” is assigned to it. The render method is used to generate HTML code with  variable interpolation.

React.render functions take a reference to the component defined and value of the property name and renders the HTML based on the second argument  “document.body” which tells React where to render the “Hello” component.

When React re-computes and re-renders component, it uses the virtual DOM(written in JavaScript). It finds the difference between previous DOM and end DOM and writes the difference only to the Browser’s DOM which makes React fast at rendering the UI.

Building a Factorial React component using Plunker

Plunker is another playground tool similar to JS Fiddle to try code without downloading the libraries.

Plunker.JPG

1. Click on Launch the Editor and click on “Live Preview”.

PlunkerLaunchEditor

The first tab shows the files available. The second tab shows the code and the third tab shows the results.

2.  Add reference to react library to the HTML page

https://fb.me/react-0.14.3.js

ref_To_React.JPG

3. Change the extension of the script file to jsx. This will tell React to parse the file as JSX and can be referenced as a js file from within the HTML page.

jsx.JPG

4.  Add reference to the script.js file into the index.HTML file

5.  Replace the h1 element with a div element with id root. This is the element which will tie React with the DOM coexisting with other elements in the DOM.

Also add a h1 element with value Factorial.

index

6. Add the following to the Script jsx

var NextFactorialButton = React.createClass({
getInitialState: function() {
return {fac:1, counter:1};
},
generateNextFac: function() {
this.setState ({ fac: this.state.fac * (this.state.counter+1) ,  counter: this.state.counter + 1 });
},
render: function() {
return (
<button onClick={this.generateNextFac}>{this.state.fac}</button>
)
}
});
React.render(<NextFactorialButton />,document.getElementById("root"));

React_Factorial_Component.JPG

The factorial component displays a button with a click event which generates the next factorial number when clicked. The factorial number displayed in the browser DOM belongs to the state of the component. The component needs to re-render itself each time the value of factorial changes. Properties could not be used here as they are immutable.

The getInitialState function initialises and returns the state object of the component. The state of the component has two elements “counter” and “fac” initialised to 1.

The value of the state element is referenced within curly braces from the vitual DOM.

{this.state.fac}

The method “generateNextFac” is tied to the onClick event of the button.  The method this.setState allows to change the state of the elements.  The “counter” element is incremented by 1 while the “fac” element is multiplied by “counter” element  added to 1.

The React.render method takes the “NextFactorialButton” component and the root DOM element where the React will display the virtual DOM which is a button displaying the state of the factorial number.

When the factorial component initially loads, the button displays 1 and on each click displays  1, 2, 6, 24, 120, 720, 5040,etc…