React – The journey begins

You could hear about React in 2015 a lot. It is a new way of creating user interfaces. Fast and easy to use. Developed, supported and used my Facebook. Sounds good! Why don’t have a look on it? That was my thinking too when I decided that I spice my extension development with this new technology.

This post will be about the some basic knowledge and about my experiences with React. I don’t want to teach you with this post how to develop in React. I have no space for that here and there are a lot of good articles about it. I will show you some sites, where to find more about React. However I need to say only the documentation of it is also a really well written source for learning React. But let’s see my thoughts about React first.

 

Why React?

You can hear about it a lot nowadays. Check what the strengths of it are and what they mean for you.

It follows the functional programming style.

The real benefit of adopting a functional style is that our programs can be broken down into smaller, simpler pieces that are both more reliable and easier to understand. Functional programs should be stateless and immutable.

Immutable means that you should simply create new data structures instead of modifying ones that already exist. It is obvious by simple types but it need to be followed by complex objects and arrays as well.

Stateless, which basically means they should perform every task as if for the first time, with no knowledge of what may or may not have happened earlier in the program’s execution. In more concrete terms, this means that your functions will operate only on data passed in as arguments and will never rely on outside values to perform their calculations.

 

Virtual DOM

It is extremly fast. Faster then any MVC fremwork rendering method or faster than template engines.

Let’s see why.  The Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details.

React includes a lightweight implementation of the DOM and events system. Manipulation of the in-memory representation of the DOM is faster and more efficient than manipulating the real browser DOM, and our events system implements all events in a cross-browser way, including bubbling.

It describes the actual state of the DOM.

You can think of template languages as a function that defines your data at time=0; with React, you define your UI in a similar way — declaratively — except it specifies how your UI looks at any point in time, not just the initial load.

 

If you change something it will be differentieted to the actual virtual DOM in memory. It is a fast operation. After that React will change only that part of the real DOM that actually changed. It isn’t a whole rerendering of the DOM.

 

Data flow

No more to way binding. If you change something you change the state and changing the state will trigger a re-render. A smart rerender as it was described in the previous block about the Virtual DOM.

Two way binding was a big thing of Angular. It was a cool feature but it has a big performance cost. Checking all the changes, the dirty values through an all time running digest circle isn’t a small amount of work in background.

I looks a cool feature but think about it. Is it worth it? Do you realy need that? It is maybe not so neccessary and you could live without it. Creating simplier user interface. Maybe you don’t need inline editable values in big list. Starting an inline editor – changing the show component to edit component – is what you could do instead and that’s the way of React.

 

JSX

JSX could be uncomfortable at first. A new syntax and why is HTML in JS? It’s from the Devil, you could think. But think again. Why is it better and more accepted writing JS in HTML than this? If you use Angular you write expressions and bind data into HTML what could lead to a lot of trouble. Misspelling something is an easy to do but painful to find thing in a programmer’s life.

JSX, writing HTML with JavaScript code together in a .js(x) file in any editor will make you sure not to misspell something.

But if you really are against it, you can write React code without JSX. Just in pure JavaScript. JSX is only a syntax sugar. It will be transformed from an XML-like syntax into native JavaScript.

 

Development environment

If you are ready to start developing you will find yourself having more options to start. It is up to you how you want to develop your React application.

TypeScript (+ gulp)

TypeScript compiler supports jsx syntax and the module loading of React. TS compiler in console is enough to do all the stuff but Gulp can make your life easier.

JavaScript ES5 or JavaScript ES6

If you are not familliar yet with the new features of ES6 or your project not in that stage yet you can still use React:

react-blog-2

You can write your React code with ES6 as well:

react-blog-3

Or use TypeScript like:

react-blog-4

After decideing the language  and the version. You can use more than one infrastructure to build your application.

Webpack or Gulp

It is only the decision of your taste.

Webpack can handle all your needs using React with ES5 or ES6.

Check a tutorial for setting up your Webpack.

You can download packages for Gulp to handle everything Webpack is capable for.

A small tutorial about configuring Gulp.

It is really good to have more options. What is a little worse that you can find examples on the internet in all different ways. You need to check always what you are looking at. Which language which version.

 

My way of thinking

 

Thinking in React is different than in Angular. You need to think in small components. You need to think in as few controller components as you can and as small components as you can.

I was coming from the Angular world. This was my first project with React. So my thinking could be strange a bit but I write it down and hope it will help someone understanding the React development concept easier.

First I wanted to see the end result of my development. It inspires me to see what I want at the end. That’s why I started with the quick build of the html tags and CSS classes. I created my first screen with mock data. So I saw what I will get at the end. Than I ripped the screen into pieces. Into small pieces.

Started with the smallest components and stepped always one up in my component tree:

  • The smallest, simplest element of my site was a list item. Done.
  • It needed a container, the list. Done.
  • And I needed the page itself. Done.
  • On the page with an “add new list item” button. Done.

So I collected all the components What I at first sight wanted and wrapped them into an every time bigger container. Added the CSS to the elements. Be careful it can be done with “className” and not with “class”. JSX sytax handles it that way.

After all of this I started to add the logic. This happened in the reverse way by me. I collected what I needed at the top level. The page itself got the logic to fill the list and handle the add new element action. After I have the list of the elements from a service I pushed down necessary info to the lower levels. It comes with so much property passing. There are solutions to handle this passing process but for now I wanted to see how it works in a pure React app. If you want to skip this try out thing that I’ve done you can jump a big and use e.g.: Redux from the start. Redux is a predictable state container for JavaScript apps. You can use it easily with React together. But more about it later.

The main concept what I used was that build your HTML code from the smallest to the biggest and build your logic from top to bottom.

As I created this skeleton of course I saw that it isn’t so simple. One list item have more small components that could be outsourced for a new component with passing some data to them. But the main concept remained the same build your HTML code from the smallest to the biggest and your logic from top to bottom. Create a big controller component at the top level with a fat state and give only the necessary data through properties to smaller components. You not just handle data through this system. Probably you want to handle changes. Changes of element on the lop level but modified at the bottom, in a small editor component. You need to pass handler functions from to to bottom as well.

That was the logic what I used to create my first pure React app. That made me see that I really need something better, a better way to handle all of this passing down work.

TIPP : In JavaScript you can add constraints about the properties you require for your components. In TypeScript you can use interfaces to define this. At first I created my TypeScript components with the state and properties of „any” – no constraints in Javascript. It was easier and quicker. At first. But after I created the first skeleton I started to change „any”-s to predefined interfaces. It helped me handle the growth of my application.

 

Development components

This components are in TypeScript. You may not need them if you are writing your code in JavaScript (ES5, ES6). But I choose this way and can show only this kind of real life example now. These components are far not all you can use. These are the main components you will run into by developing a small application.

Component

These are the main building blocks of your React application. It is an extended class. You have to handle the state, the props, the render function and all the lifecycle methods are available.

You can have private methods and private properties as well. All of these will give you an element that have a HTML representation and optional some logic.

Here is an example:

react-blog-7

State

You can initialize your actual state in the constructor of your component. After that you can set the state any time in two different ways and all the changes of the state will trigger the call of the component’s render method.

setState({mykey: 'my new value'});

setState(function(previousState, currentProps) {
  return {myInteger: previousState.myInteger + 1};
});

If you change the state implicitly (eg: data deep within an object changes without changing the object itself) or if your render() method depends on some other data, you can tell React that it needs to re-run render() by calling forceUpdate().This will trigger the normal lifecycle methods and will still only update the DOM if the markup changes.

Properties

Properties are coming from the parent component as a constructor parameter of your actual component.

Lifecycle

I will show you a small example of it in TypeScript

And here is the description of all the lifecycle events you can use. It is a short and simple description of them. Didn’t wanted to just copy paste it.

The documentation from the official site.

Routing

React is for UI handling. It makes rendering easy and fast but not cares about other things. Routing is something that you may need for a smaller app as well. Like for me developing a browser extension.

It comes to React as an additional package. You need to install react-router with npm. Include into your sources.

For TypeScript users there is a React-Router d.ts beside the JavaScript sources.

Using the routing is not so difficult. Just define your routing at first and you get the navigation.

react-blog-6

TIPP : There is one typings for Routing if you use tsd install but you can get an extended d.ts for Router from this link.

TIPP : In some examples there is a context.router but instead you can use the context.history in TypeScript.

TIPP : Passing properties through the navigation is not an obvious thing. Look after this two options.

RouteHandler component. It can have properties that will be available for all the components loaded into the place of the handler.

Or something similar to this concept but a custom way. Writing a wrapper component as the route handler component and this wrapper component will contain the data you want to pass and gives access through properties to the contained component.

More info.

 

Flux – Redux

Flux is the application architecture that Facebook uses for building client-side web applications. It complements React’s composable view components by utilizing a unidirectional data flow. It’s more of a pattern rather than a formal framework, and you can start using Flux immediately without a lot of new code. You can find a lot of implementations of the flux architecture, e.g.: Redux or Reflux.

Redux holds your application state in one place, and defines a minimal but sufficiently powerful way of interacting with that state.

Reflux is a simple library for uni-directional dataflow application architecture with React extensions inspired by Flux. It takes the Flux approach and streamlines it, making it both easier to work with and easier to grasp.

I hope I will have time to refactor my pure React extension and integrate the use of Redux into it. Of course I will blog about it as well. So keep visiting my site and hopefully someday in the near future it will be a blog post about it.

But until then check these cool articles in the theme:

A compare of implementations.

A flux – reflux comparison.

A Redux article.

The official Redux site.

 

Summary

I really liked using React. These were my first steps. Maybe for a veteran React developer there were some funny thing but I will stay on this road and will deepen my knowledge. Hope that someday I will smile on this article too, but that’s how I started that’s the way I could adopt at first this new world and hope it will help you.

If you want something really fast working component I would use React. A component. As a developer it isn’t so fast to use. If you want to write clean and nice code in React you need to do a lot of refactor through your development. So much small iteration. If you find something that you could break for a smaller, dummier component you better do it. If you need a new object or just a property to handle probably you need to pass it down from upper – controller – levels to deeper to dummy components and writing the change handling of it and so on.

As I experienced writing a whole application in React (React + something flux) is complicated. Other usage of React could be that you writing components in React and using them in an Angular project. You get the whole infrastructure that makes your life easy and you can use fast rendering components. I will give a shot to that too, will try to replace a component in our huge Angular project. Seems as an interesting work to do. That will maybe a new theme for a later blog post. Check my site and you may see it published someday. J

These were my thoughts about React but I’m interested in your ideas and opinions. Feel free to leave a comment so we can discuss them.

 

Some sites I can recommend

React official site.

Functional programming @ SmashingMagazine.

React @ SmashingMagazine.

React getting started @ RisingStack

React best practices @ RisingStack

React goodies 1

React goodies 2

Advertisements

React with TypeScript

Introduction

 

If you red my previous posts you probably know that I currently develop an extension in TypeScript.

For implementing the UI part of the extension I chose React. React because it is super hyped nowadays, I was interested and always good to learn something new.

About React itself and about the development details developing with React it will be an other post as it is planed. But I thought this part of my journey with React deserves a separated post.

Let’s see how I get together React and TypeScript for my extension.

 

Start getting TypeScript together with React

 

The release of TypeScript 1.6 includes support for React components.

That means you don’t need to use any module dependency handler, like Browserify to handle React modules.

It’s really nice. Let’s try it out!

You install typescript with npm:

npm install –g typescript

You check the version you have installed:

npm view typescript version

It is the newest. 1.6. Cool!

Try to use the tsc compiler with ––jsx or with ––project (including jsx handling as well).

 

The first problem

 

Do you have Visual Studio installed to work sometimes with that too?

Yes? – That’s the problem!

I work on Windows with WebStorm 11 but for other projects I have Visual Studio 2015 installed as well.

Visual Studio makes its compiler for windows as default. Command line will try to use it first.

 

Solutions

 

Check your Visual Studio folder:

C:\Program Files (x86)\Microsoft SDKs\TypeScript

Does it contains any TypeScript versions under 1.6?  Yes?

  • Solution 1

Upgrade the Visual Studio’s TypeScript from here.

  • Solution 2

Just delete the older TypeScript versions.

  • Solution 3

Set an explicit system variable pointing to the npm installed version of TypeScript compiler.

 

 

Getting TypeScript together with React

 

After letting this problem behind you can try out the TypeScript compiler.

Install React and ReactDOM with npm.

npm install –save react react-dom

Install typescript definitions for them with tsd.

tsd install — save react react-dom

If you are using modules you should use react.d.ts, react-dom.d.ts and any of the react-addon-*.d.ts definition files.

Use them in modules you need:

import React = __React;

import ReactDOM = __React.__DOM;

If you are using the global React variable, you should use react-global.d.ts.

You need to download the react-global.d.ts file from the DT site and copy it under the typings/react folder.

Include React and ReactDOM in index.html. (From CDN or from your sources.)

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

 

Create your UI

 

Write your demo button .tsx file:

react from extension

If you didn’t handle page load in your code and include your scripts into the head, you probably will face the following error in your inspector console.

Uncaught Error: Invariant Violation: _registerComponent(…): Target container is not a DOM element.

A quick fix could be if you write your script tags at the bottom of the body tag. Handling all of this is better from code I think. I wrote it down just because if you see this error this is the fastest way to move on.

react from extension

Including scripts at this point of your site isn’t from the devil. With React you have the option to do that and you can read a lot of good thoughts about the benefits of including scripts this way.

Having to code is one thing you. You need to create a deploy-able package from your source.

 

Compile for publish

 

You can do it from command line manually with tsc. You only need a good configuration json.

tsc –project tsconfig.json

Or you can choose an automated way, using Gulp. Gulp could be good for handling other automatized tasks as well. In this post we will check only the typescript compiler task of it.

You need to require the TypeScript compiler:

var ts = require(‘gulp-typescript’);

And use the “createProject” method of it. It will create a configured project according to the settings in your json file.

The project’s src is defined in the files section of the json config file (if not all files will be included).

react from extension

Let’s see the magical tsconfig.json file that we could use for the command line compiler and for the gulp task as well.

react from extension

For all setting options detailed, visit the following sites.

Schema description. Just the facts.

Github wiki with more explanations.

If you don’t have a lot of options and you don’t want to outsource it to a json file, you can configure the ts compile in the gulp file as well.

react from extension

 

Run it and it will work fine!