Don’t be afraid of React — library guide

Merixstudio
WDstack
Published in
7 min readJul 1, 2016

--

React is library from Facebook and Instagram, created for building composable user interfaces. It perfectly fits in large applications with dynamically changing data. It’s often compared to V (View) layer in MVC. Main concept is to build reusable UI components which are displaying data and when that data changes it simply “rerender” that component using new data.

Why React?

You can ask yourself: When and why I should choose React as View layer for my application? You will find out in my article, where I’ll present some usage examples!

First of all, React is very simple in terms of the concept — check out the main concepts that are used in React:

Component

It’s a Javascript object that is representation of DOM node. Each component may contain another components (it’s called component tree). That allows to break each component into smaller chunks, which are easier to test and maintain, and can be reused in other components.

Reactive updates

It’s the most important feature. Like I said before, UI is “rerendered” each time when data changes, therefore we only need to care about how data is displayed within component. With the usage of Virtual DOM React diff algorithm you can easily determine what pieces have changed and render only elements that’s need to be updated — it’s very efficient method of work.

JSX

It’s Javascript syntax extension that make writing React components code easier — you can read more about it here. P̶l̶e̶a̶s̶e̶ ̶b̶e̶ ̶a̶w̶a̶r̶e̶ ̶t̶h̶a̶t̶ ̶I̶’̶l̶l̶ ̶b̶e̶ ̶u̶s̶i̶n̶g̶ ̶E̶S̶6̶ ̶s̶y̶n̶t̶a̶x̶ ̶a̶n̶d̶ ̶d̶o̶n̶’̶t̶ ̶b̶e̶ ̶u̶s̶i̶n̶g̶ ̶J̶S̶X̶ ̶i̶n̶ ̶t̶h̶i̶s̶ ̶a̶r̶t̶i̶c̶l̶e̶.

EDIT: There was mistake here. JSX actually is used in this article code snippets. What I was meant is that we are using Babel ES6 including JSX transformer.

Component Architecture

Components are fundamental part of React — they can represent some kind of widgets or modules. They define how DOM elements are created and how user can interact with them. I’m going to describe basic concepts that are necessary to know when you want to work with React Components. For more experienced developers i highly recommend this article, where you will read about detailed specification of components.

Properties (Props)

Properties are used to pass some additional data to the component, what is very useful when we want to customize our compontents. Properties are defined as attributes in HTML elements.
Here’s example of using properties in React components.

First of all, we define simple Greeter component

import React from 'react'; 
exports class Greeter extends React.Component {
render() {
return (
<div>Hello {this.props.name} !</div>
)
}
}

As you can see, properties can be accessed inside the component by this.props which is object with property name as key and property value as object value.
Example of the usage of component:

import React from 'react'; 
import Greeter from './greeter';
export default class App extends React.Component {
render() {
return (
<div>
<Greeter name="Bob" />
</div>
)
}
}

After completing these steps, the Greeter component then will render because name property with value Bob was passed to the Greeter component.

<div>Hello  Bob!</div>

Property types (propTypes)

Inside the component we can also define propTypes which are used for type validation. Let’s say that our Greeter can only accept name property with value of String type.

import React from 'react'; exports class Greeter extends React.Component {
render() {
return (
<div>Hello {this.props.name} !</div>
)
}
}
Greeter.propTypes = {
name: React.PropTypes.string
}

As you see, we added `propTypes` object to the `Greeter` object. That’s how we define `propTypes` when using ES6 syntax.

Greeter.propTypes = {
name: React.PropTypes.string
}

You can read more about propTypes here

State

Similar to properties, state also affects how a component behave and render. However, it only can be accessed inside component definition and each component has its own state. It should be considered as private data inside compontent.

State object can be accessed like properties object — by using this.state. You can find further information about states here.

Alternative tools

React is not the only library that works in that way — Polymer, Riot.js or Om are also frequently used. React surely has a big community and developers team from Facebook behind it, what can be seen as a big advantage. However, all of these component driven libraries, even when somewhat different, perform the same task.

React vs Angular

React and Angular are almost impossible to compare — the first one is UI library (the V in MVC), when the second one is full fledged frontend MV* framework. What’s more, React even can be used within Anuglar as View library.

Only thing that I can compare, it’s templates and directive system from Angular to React modularity. Personally I think that React gives more control and easier data management between components than Angular between directives and controllers.

How to start working with React?

There’s a bunch of boilerplates to choose from when you want to start working on React backed project. Anyway, I’ll show you how to start simple React project from scratch.
You can write React code in ES5 or ES6 syntax. I’ll show you how to use it with ES6 using Babel and Webpack. But remember, it can be configured to be used with other build tools.

Initializing a project

First of all, we have to create directory for our project and initialize npm project. To do that simply call:

mkdir  react-project  &&  cd  react-project 
npm init

After that we need to install webpack module bundler from npm. Remember — we need install it globally and locally for out project!

npm install -g webpack 
npm install --save-dev webpack

After installing webpack, we need to create config file for example webpack.config.js

module.exports = {
context: __dirname +' /app',
entry: './app.js',

output: {
filename: 'app.js',
path: __dirname + '/dist',
}
}

That config file define that our application files are located in /app folder and our entry point to our application is app.js. We also defined that our bundled application will go to the dist/app.js file.
Finally we need to create app/app.js. We will add something simple for now:

console.log('Application started');

Loaders

Main concept of Webpack is Loaders. Loaders are plugins that are transforming our JavaScript code. For React we need jsx-loader and for ES6 we will use babel-loader. New Babel 6 release has new architecture, so we need babel-loader and babel-core. For support of JSX syntax additionaly we need babel-preset-react and for collection of ES6 transforms — babel-preset-es2015.
We need to install it by calling:

npm install --save-dev babel-loader babel-core # For ES6/ES2015 support 
npm install --save-dev babel-preset-es2015
# For JSX support
npm install --save-dev babel-preset-react

Runtime support

Because ES6 syntax is not fully supported by most browsers, and Babel can’t provide support only with compilation, we need to add polyfils. We need to simply install:

npm  install --save babel-polyfill

We will also need to install some packages to simple bundle all needed helpers to our code, instead to include them one by one when needed.

npm install --save babel-runtime 
npm install --save-dev babel-plugin-transform-runtime

After installing all modules we need to configure webpack to use Babel, our webpack.config.js file now should look like this.

Note: Look at entry section, I’ve included babel-polyfill to our output file for extended browser support.

module.exports = { 
context: __dirname + '/app',
entry: [
// Set up an ES6-ish environment
'babel-polyfill',
// Add your application's scripts below
'./app.js',
],
output: {
filename: 'app.js',
path: __dirname + '/dist',
},
module: {
loaders: [
{
loader: 'babel-loader',
// Exclude /node_modules directory
exclude: /node_modules/,
// Only run `.js` files through Babel
test: /\.js$/,
// Options to configure babel with
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'react']
}
},
]
}
}

React

Finally, now we only need to add React to our project and start writing the code. We will need two install packages react and react-dom.

npm install --save react react-dom

Example od usage

When we have everything else ready, let’s use our Greeter component and render it on the page

// greeter.jsimport React from 'react'; export default class Greeter extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<div>Hello {this.props.name} !</div>
)
}
}
Greeter.propTypes = {
name: React.PropTypes.string
}
// app.js import React from 'react';
import ReactDOM from 'react-dom';
import Greeter from './greeter';
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Greeter name="Bob" />
</div>
)
}
}
// Render main app component into DOM
ReactDOM.render(
<App/>,
document.getElementById('app')
);
// index.html <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body> <div id="app">
</div>
<script src="dist/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
</html>

In the last step we need to run webpack command

webpack

After a while, it should print little summary of webpack transform. Then you can run index.html from your local webserver and it should print Hello Bob! message.

Summary

I think that I explained the basics of working with React. This guide only covers running an React project and creating simple component, but it’s enough to go deeper into the React development. To do more complex stuff you probably will need to integrate it with some more complex architecture like Flux or Redux. Presonally I’ve used React with Redux in one of my projects, and I’m very excited about it — you should try it too!

Originally published at www.merixstudio.com.

--

--