React on Steroids
Tips and Tricks from a Functional Programming Expert

ReactJS Israel - January 2017
Yehonathan Sharvit


		(new Date()).toString()
            

Who am I?

  • A mathematician
  • A pragmatic theorist
  • A coder
  • A freak of interactivity
  • Barclays - head of functional programming
  • Founded a Audiology Startup with 30K LOCs in Clojurescript
  • Author of KLIPSE

Agenda

  • KLIPSE - Code interactivity everywhere
  • Functional programming - Paradigms and examples
  • React.js - a functional frontend framework
  • React.js - Functional tips and tricks

KLIPSE - Code interactivity

KLIPSE is a javascript tag that transforms pieces of static code into interactive code snippets

Data Manipulation


	      [1,2,3].map(x => x + 1)
        

console.log


	      console.log("Hello World!")
          

Asynchronous code


	      setTimeout(() => console.log("Hello World!"), 1000)
          

KLIPSE - Code interactivity

Open up your Laptop for a collaborative live coding session: slides.klipse.tech

(Might work also on mobile)

/

KLIPSE - Dealing with the DOM

Hello World


	    klipse_container.innerHTML = `<div>Hello <em>World</em>!</div>`
	    "trivial"
	

Hello World - with style


	    klipse_container.innerHTML = `<div>Hello <em style="color:red;">World</em>!</div>`
	    "nice"
	

More interesting - SVG


	    klipse_container.innerHTML = `<svg width="100%" height="400" viewBox="0 0 300 200">
	    <path d="M3.9,74.8c0,0,0-106.4,75.5-42.6S271.8,184,252.9,106.9s-47.4-130.9-58.2-92s59.8,111.2-32.9,126.1 S5.9,138.6,3.9,90z"
	    fill="none" id="theMotionPath" stroke="brown"/>
	    <g stroke-width="2" stroke="black" fill="white">
	    <circle r="20"/>
	    <circle r="2" cx="-7" cy="-5"/>
	    <circle r="2" cx="7" cy="-5"/>
	    <path d="M -10 5 Q 0 15 10 5"/>
	    <animateMotion dur="4s" repeatCount="indefinite"  rotate="auto">
	    <mpath xlink:href="#theMotionPath"/>
	    </animateMotion>
	    </g>
	    </svg>`
	    "cool"
        

KLIPSE - how to integrate on your blog

Super Simple!
You include the klipse javascript tag on your page.
You specify the CSS selector of the DOM elements that you want to klipsify.

More details on github.

Functional Programming - Immutability

In non-functional programming, the default API mutates our objects


                const a = {size: 42};
                b = a;b.size = 43
                a
            

EcmaScript 6 got inspired by functional programming - and propses an immutable API:


                const a = {size: 42};
                b = Object.assign({}, a); b.size = 43
                a
            

Does it work as expected?


              const a = {size: {shoes: 42}};
              b = Object.assign({}, a)
              b.size.shoes = 43
              a
          

Functional Programming - Immutable.js

Let's load Immutable.js from a CDN
By setting data-external-libs="https://raw.githubusercontent.com/facebook/immutable-js/master/dist/immutable.min.js" to the DOM element of the klipse snippet:


		 !!Immutable
             
Now, we can play with immutability:

		 a = Immutable.fromJS({size: {shoes: 42 }});
		 b = a.setIn(["size", "shoes"], 43)
		 a
               

Functional Programming - Immutable.js

It is fast!
It relies on mapped tries that were first implemented in Clojure .
Going deeper:

Functional Programming - High order Functions

High order functions are functions that:

Functional Programming - Ramda.js

Ramda - A practical functional library for JavaScript programmers.

Let's load Ramda.js from a CDN
By setting data-external-libs="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.23.0/ramda.min.js" to the DOM element of the klipse snippet:


		 !!R
             

Functional Programming - Ramda.js

partial takes a function f and a list of arguments, and returns a function g.
When applied, g returns the result of applying f to the arguments provided initially followed by the arguments provided to g.


	      var greet = (salutation, title, firstName, lastName) =>
	      salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';

	      var sayHello = R.partial(greet, ['Hello']);
	      sayHello('Mr', 'John', 'Smith')
          

We can compose partial functions:


	      var sayHelloToMs = R.partial(sayHello, ['Ms.']);
	      sayHelloToMs('Jane', 'Jones')
	  

React.js: the functional frontend framework

The principles

  1. Virtual DOM

  2. Immutability

  3. Pure functions

React - Tic Tac Toe




Based on Tutorial: Intro To React.

React - The basics

Let's load react javascript files from cdnjs.com:


	  !!React
      

Tic Tac Toe - Square: a pure component


      

            ReactDOM.render(React.createElement(Square, {value: 42,
            onClick: () => alert("clicked")}), container)
	

KLIPSE and JSX - Under the hood

The page source

Tic Tac Toe - winner

How do we decide who is the winner of the game?

There are only 8 possibilities to fill a row in the board

function calculateWinner(squares) {
	  const lines = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6],];
	  for (let i = 0; i < lines.length; i++) {
			      const [a, b, c] = lines[i];
			      if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
			      return squares[a];
			      }
			      }
			      return null;
			      }
			      

Tic Tac Toe - with players


        ReactDOM.render(React.createElement(BoardWithPlayers, {}), container)
    

Tic Tac Toe - with history


        ReactDOM.render(React.createElement(BoardWithPlayers, {}), container)
    

Summary

Questions?

powered by KLIPSE /