Getting started with React.js

As a lead developer, I watch the web development market for solid trends (not the hype ones), and see if they could be a tangible addition to our workflow. Like Angular a few years ago, React has gained enough momentum to catch my attention. I decided to try it out in a side project to get a better understanding of how it works. Here are a few things I've noted from our first encounter. This is a beginner's point of view, not a React expert's one, so if you see any mistakes, don't hesitate to let me know, I'll update the article accordingly.

First of all: what's React?

That's the first question I had and wanted an answer to. When learning a new framework or a new language, the first thing you need to understand is what you are going to be dealing with, right? What's the core concept, how does it work, what's the philosophy behind this tool, why people think it's great, what are the argument against? I wanted to find an answer to most of theses questions, because usually, the more precise your understanding is, the less time you are going to loose.

I know it's all exciting, shiny and new, and you can't wait to dive into the coding and spit out some React awesomness like the cool kids. But I know by experience that if I don't take the time to investigate first, the first output is usually far from awesome :), and stepping right into the code usually doesn't make you gain time on the long run.

Before we start, some key points

Like most of us have probably done, I headed to the offical React website. I took a tour of the documentation looking for my answers. Here are some key points I found worth noting, either because they were really important, or because they mattered and weren't that obvious to me. Hopefully these few thoughts will help you along your own discovery of the tool.

In which context do you use React?


If you are considering an MVC structure, React says it's mainly used as the V. It comes in at view level, it doesn't force you into a particular architecture or technological stack, which means it's not a full blown framework like Angular for example. That's an advantage in a sense that you are free to use whathever you want to handle the routing in your app and your model definitions. You could use Angular indeed, or backbone to take care of the M and C parts for you.

This can also be seen as a disadvantage because when building an app, it's rare to only use the V part. That's all good to be free to use whatever you want, but by default you get nothing in terms of routing so either you incorporate another third party script to handle it, or you'll have to code it yourself.


React has a reputation for being very fast. Why?

It's proven that when building JavaScript applications one of the slowest interaction is accessing and manipulating the DOM. To avoid this, React maintains a virtual copy of the DOM with which your code interacts. When a change is supposed to happen in the real DOM, it is first submitted to the virtual DOM. React compares its virtual DOM with the real DOM, computes a list of changes to perform, and batch applies only those specific changes to the real DOM. It reduces unnecessary DOM changes and repaints, which is indeed an interesting logic.

Here I'll introduce a first counter argument I've found in this article or this one against this approach: Maintaining a fresh copy of virtual DOM, comparing it with the actual one, and updating it, are operations made possible by a non negligeable quantity of code and processing that costs time as well. I find this argument interesting because it tries to go beyond the hype, and I find this important with new tools like this. When everyone's happily shouting on Twitter: "React is awesome, it's super fast, it's backed by facebook!" I like to see points of views from people that actually took some time to understand why it was considered fast and if that was really true.

I'm not saying React is not fast, I'm just pointing at the fact that when investigating a new technology, I like to have different point of views, to better assess its advantages and shortcomings.

How to think and code in React?

I think the best way to get started with a new technology is to understand its philosophy. In React's case, there's a page that summarize's its thinking very well: Thinking in React. To summarize: everything is a component, which means you need to understand what a component is, how do you write one, and how to work with it.

Components core concepts

For me, the key concepts to understand when getting started with a component are the React.createClass call (to create a component), the render method (that gets called when displaying the component), the state, the props. It's all demonstrated in React's first example, where you can see how to create a component, to implement the render method, and to pass in props as attributes of the render method.

  1. var HelloMessage = React.createClass({ //Create a component
  2. render: function() { //Implement the render method
  3. return
  4. <div>Hello {}</div>
  5. //Access props
  6. ;
  7. }
  8. });
  9. React.render(<HelloMessage name="Jeremy" />, mountNode); //Render passing props

At this point you might have noticed that you are in a .jsx file, and that in this file, you write some js and some sort of HTML. you might be wondering: "What's this strange syntax?" Well, that's JSX. It's noted in the documentation that using JSX is not mandatory to use React, but every tutorial is in JSX, and that's the format they advise you to use so trying to code without would be difficult.

JSX support is not native, which means that somewhere in your dev process, you'll have to compile JSX into JS

If you are still with me and convinced that this is the tool you need, let's dive into some proper action.

Getting to work

How do you install React?

React's source

The React source can be used as a script file in your html page, included via Bower, or via npm, it depends on your use case. Including it in your html file directly is probably the most straightforward way of using it. Using bower or npm requires a bit more setup but is probably more interesting in the long run, especially when dealing with jsx as well. Furthermore, it's unlikely to build a website without a task automator like grunt or gulp these days, which means that if you integrate React and the JSX compiler in your build process, you'll have in the end a bundle of JavaScript nicely concatenated and optimized.

I've tried to use React directly, and via Bower. It seems the best option is to use the commonJS syntax provided by the node module, especially because it opens possibilities to render your components server side, and it's easier to test them (React's testing suite Jest uses commonJS syntax).

To summarize, if you have a build process, I'd go with npm, if not, you can still include React's source directly in your HTML.

JSX transformation

Here again, you have several choices: You can include the JSX transformer in your HTML file, then use some Script tags for your JSX. The transformation will then be done directly in the browser.

Second option, like the React source, if you have a build process, it's probably better to include the JSX transformation to this process as well. This way, your JSX files will be transformed to JS automatically by the task automator, and you'll have optimized Vanilla JS files included.


To be more precise about my setup, I've been using grunt as a builder, with a few modules such as grunt-react (to transform JSX files to JS), grunt-contrib-concat (to concatenated all my JS files into one), grunt-contrib-uglify (to compress and optimize this big file) and grunt-injector (to dynamically insert the optimized script source into my HTML page). To automate this all, I've used grunt-contrib-watch, and configured it so it automatically compiles the JSX files as I modify them.

In terms of file structure, because we are working with files that are meant to behave in a modular manner (one file per component for example), and that are supposed to be transformed for production (from JSX to JS), I've tried to separate the dev environment, and the production environment.
To be more concrete, a few folders concern the dev environment: I have a node_modules folder for everything required by grunt, one bower_components folder for third party dependencies (like React), and one app_components folder where I put my JSX files and my LESS files. When I compile my project, grunt serves optimised assets in the production folder www, where I'll have the compiled CSS and JS.


Grunt's watch task is hooked on the JSX folder for automatic compilation into JS when a change is made to any file in there.

To complement what I said earlier, if I had to do it again, I'll probably ditch bower in favor of commonJs modules, with webPack of Browserify (to open possibilities of server side rendering and easier testing).

You should now have access to the React source, and be able to code using the JSX syntax. It's time to get coding. At NOE we use NetBeans as our IDE, and as I'm used to it, I usually stick with it when coding personnally, but it's not ideal to code in JSX as it doesn't support its syntax at this point, and I haven't found a good enough plugin. The WebStorm IDEs seem better for this. SublimeText and Coda both have a React package.

Thinking in React

Here again I'd like to redirect you to the Thinking in React Page as it's well explained and it's a crucial part. At this step, the idea is to break your UI into components focusing on a particular task, those components will then become React components.

To learn React, I wanted to recode a little side project of mine I had previously done in jQuery, because it was a concrete and focused case, and it would allow me to appreciate the difference of coding between the two tools. This side project is called ambiGhue, and it's an ambilight web app for philips Hue smart bulbs. The idea is to put your computer in front of your TV, the computer will look at the TV screen through its webcam, extract the most dominent color off the image, and send it to the bulbs. This way the atmoshpere in the room would change according to what you are watching.

Below are the different screens, and for each I've outlined how I cut them into 7 components.

_app + _bridge
_app + _user
_app + _light
_app + _lightList
_app + _ambilight

State vs props

There are two types of "model" data in React: props and state. The state is a data definition used for interactivity within the model, usually a change in the state triggers a new rendering of the component. Props are passed to the component by a call, a bit like parameters passed to a function call. When you only have one component, props are passed by the explicit render call, like React.render(, document.body);. When you have a parent component with children components, the parent can pass props to its children from within its own render method.

What I found difficult at first with React, is that I only found examples with single components, or components with a few children components, but what I needed was a way to change components based on certain conditions. I found out that you can use one parent component that could be the bandmaster. It would be the component that would own the state of my little application, and that would render the different children component accordingly. This seems to follow React's philosophy that specifies that you need to find a common owner component (a single component above all the components that need the state in the hierarchy). A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props.

This part was also a bit difficult to understand for me because I started my research having in mind that a React component is a View, but I started to realize that in some cases, a component could act as a Router, like my _app one that renders a component or another based on it state, or it could behave as a model, fetching data from the database for example, which is something I usually do in a model.

Precisions regarding each component

As we've just seen, the _app component would be the bandmaster of my little app, would own the state, and trigger the rendering of different sub components, passing them props, so based on my app's functionnality, in its state, I'm defining elements that would allow me to render a child component or another.

To explain the different elements I've put in the state, here's the scenario of my application's behaviour:

  1. Philips Hue lights work with a bridge. Any third party app wanting to interact with the lights needs to register with this bridge first. That means we need to find the bridge's IP address, and send him a connection request. This step is the purpose of the _bridge component, whose functions would be to locate the bridge, keep its IP address, and make him connection requests.
  2. This bridge is secured, and only allows known and accepted app ids to interact with him. When an app makes a connection request, the bridge owner needs to push a button on the bridge to inform him the app is known and allowed. When the button is pushed, you can store the app id for later use without pushing the bridge button again. This step is the purpose of the _user component, that would register the app with the bridge, and store the authentication token for later use.
  3. When the app is ready to interact with the bridge, it makes another call to its internal API to get the list of available lights from him. This would be the purpose of the _light component, that would query the API and store the lights list
  4. When the app has found lights to interact with, the list is displayed to the user, so he can choose which ones; he wants to ambilight with. This is achieved using two components: _lightList and _lightRow
  5. Finally, when the user has selected one or several lights and pressed the start button, the final component, _ambilight, starts the ambilight mechanism.

As a result, in my _app component state, I'll store data regarding the bridge, the user, the list of lights, and the selected lights for the ambilight. You'll find the code that defines the app initialState here.

  1. getInitialState: function() {
  2. var defaultUser = '';
  3. if({
  4. defaultUser = localStorage.getItem("hue.user");
  5. }
  6. var state = {
  7. splashing: this.props.splashing ? this.props.splashing=="1" : false,
  8. bridge: {},
  9. user: defaultUser,
  10. lightsList: [],
  11. selectedLights: [],
  12. ambilighting: false,
  13. delay: 1000,
  14. error: null
  15. };
  16. return state;
  17. },

Based on those values:

  1. If I don't have a bridge, I'll render the _bridge component
  2. If I have a bridge and no user token, I'll render the _user component
  3. If I have a bridge and a user token and an empty light list, I'll render the _light component.
  4. If I have a bridge, a user token and an light list, I'll render the _lightList component, that would render each light in a _lightRow component.
  5. If I have a bridge, a user, a list of lights as well as a list of chosen Lights, I'm ready to render the _ambilight component as soon as the user presses the start button.

As you can see in this breakdown, I'm using lots of if conditions. It turns out React doesn't allow you to use if statements in your render method. I've found an example in this article where the coder used ternary statements instead of ifs, and that seems to be allowed, so I've tried it as well. It does effectively work, but I find the syntax a bit heavy. It gives us the following render method

  1. render: function() {
  2. var t = this,
  3. classes = [];
  4. if(this.state.splashing){ classes.push('splash'); }
  5. if(this.state.ambilighting){ classes.push('ambilighting'); }
  6. return (
  7. <div id="app-wrap" className={classes.join(' ')}>
  8. <div id="app-container">
  9. <div id="app-top">
  10. <div id="logo-wrap">
  11. <span id="logo">
  12. <span className="ambi">ambi</span>
  13. <span className="g">g</span>
  14. <span className="hue">Hue</span>
  15. </span>
  16. </div>
  18. </div>
  19. <div id="app-bottom">
  20. <div id="stage">
  21. {!this.state.splashing && ! ? <_bridge /> : ""}
  22. {!this.state.splashing && && !this.state.user ? <_user bridge={this.state.bridge} /> : ""}
  23. {!this.state.splashing && && this.state.user && !this.state.lightsList.length ? <_light bridge={this.state.bridge} user={this.state.user} /> : ""}
  24. {!this.state.splashing && && this.state.user && (this.state.lightsList.length>0) && !this.state.ambilighting ? <_lightList lights={this.state.lightsList} toggleLight={t.toggleLight} selectedLights={this.state.selectedLights} startAmbilighting={t.startAmbilighting} /> : ""}
  25. {!this.state.splashing && this.state.ambilighting ? <_ambiLight bridge={this.state.bridge} user={this.state.user} selectedLights={this.state.selectedLights} stopAmbilighting={t.stopAmbilighting} /> : ""}
  26. </div>
  28. </div>
  29. </div>
  30. </div>
  31. );
  32. }

It was a surprise at first for me, not to be allowed to use some basic if conditions in the code. Why such a restriction? I tried to find some elements of anwser in the documentation, and I found those: One of the reason is because of the way JSX is then translated to native JS. When you look at examples in the doc of JS version of the render method, you can see that it couldn't be compatible with statements. Second reason, a component should have a given functionality, adress one given problem, it needs to be focus and simple. If you start to have the need for conditions, maybe you could split your problem into two sub components instead. Third reason, a component should be very predictable, and always return the same output given the same state. That's one of React's fundamental for speed and VDOM comparison.

I'm not a big fan of all those ternary statements. It looks dirty and difficult to read. Maybe it would be better to store the current child component in the state? What do you think? If you've done this before, how did you tackle this? Apparently, that's what they seem to suggest here: If a ternary expression isn't robust enough, you can use if statements to determine which components should be used.

At least it works how I intended, based on the state, it renders a different child component accordingly, passing them the props they need to perform their function.


Instead of reviewing each component's code in depth, which would be repetitive and not that insteresting, I've listed a list of challenges I've faced and for each, what the solution I found was. Don't hesitate to let me know what you think of the solution, and how you would have done if you think that it's not right.

Ajax calls

That's the second challenge I encountered in my application after the sub component rendering based on state. The app needed to find the bridge IP address to communicate with the lights, and this is possible by making an ajax call to a special URL ( made available by the bridge itself. So by which mechanism do you make ajax calls in React? and when do you do it to load data in the component?

If you compare this with Angular, which is a full framework, you'd answer those two questions by saying you'd use the $http module in a factory for example. But React is not a full framework, and does not give you any prepared object to make ajax calls, which means that you'll either have to use the native XHR object, or use another one already made, like the jQuery methods for example. As jQuery is loaded in my application, I've decided to use the $.post or $.get methods when needed.

As a component is rendered, or removed by the master component, the ajax call needs to be done at a precise point to fetch initial data in ajax into your component. There's a page in the documentation that explains how to make this initial call, you need to put it inside a method called componentDidMount. This method is in fact part of a set or pre defined methods called at specific points of a component lifecycle, which are quite interesting to know. I've found componentDidMount and componentWillUnmount particularly interesting for example.

Concretely, in my app, here's how I locate the brdige IP in my _bridge component:

  1. componentDidMount: function () {
  2. this.lookForBridge(); //Make the ajax call in the componentDidMount method
  3. },
  4. lookForBridge: function(){
  5. $.when( hueApp.connector.discoverBridge() ).then( //Actual ajax call (promise)
  6. function( bridge ) {
  7. //Success, I have the bridge info
  8. },
  9. function(error) {
  10. //Error
  11. }
  12. );
  13. }

To summarise, to make an ajax call, choose your carrier, and make the call in the componentDidMount method.

Communicating between components

Another challenge that I quickly faced. How do you communicate between parent and children components? As a follow up of the bridge localisation we've just seen in the ajax calls challenge, let's says I've made the call, I've found the bridge information, but I'm in the _bridge component, and I'm not the one holding the state, my parent (_app) is. So how do I tell him that I've found the bridge so he can put it in his state and render the _user component next?

Apparently in React, like it's explained on this documentation page there seems to be two ways of doing this, by passing event handlers via props, or via a pub/sub mechanism. My previous implementation of the app in jQuery made use of the pub/sub mechanism, so I kept it for the _bridge, _user and _light components, but when you have a parent / child relationship, it's probably better to pass event handlers via props.The Pub/sub is more for when you don't have a parent/child relationship. If I had to do it again, I'd probably rewrite the _bridge, _user and _light components to pass event handlers via props. I've done so in the _lightList component for the click event on the start button:

In the _app component, I've defined the click handler, and passed it to _lightList:

  1. //The startAmbilighting memthod is part of my _app component
  2. startAmbilighting: function(){
  3. var t = this;
  4. t.setState({ambilighting: true});
  5. }
  6. //When rendering the _lightList component, I pass the startAmbilighting callable via props:
  7. <_lightList startAmbilighting={t.startAmbilighting} lights={this.state.lightsList} toggleLight={t.toggleLight} selectedLights={this.state.selectedLights} />


When I change the state of my _app component, it renders a child component or another and does so very quickly. For example, it looks for the bridge information, and as soon as it finds it, the _app component changes state, removes the _bridge component, and renders the _user one in a snap. It would be better to animate the change between the two components so the _brdige one could scale and fade out, while the _user one scales and fades in for example. There's a special page in the documentation dedicated to animations, especially performing animations when a component enters or leaves the DOM. I haven't tested this in my app, but that's something I'll probably do next time I'll work on a React project to get a better understanding of how it works. Have you tested it yet? Any examples of implementations you'd like to share?


I'd say around 90% of the latest projects I've been involed in, included some multi lingual aspects, so I wanted to try to think the architecture of this app with built in translation capabilities.

Here again, unlike Angular which provides built in translations mechanisms, there's nothing available by default in React, so you need to build your own or use something already made by someone, such as this component for example. I've coded my own system which seemed lighter but less portable. It works as follows. I have a translation object, that you can find here, and that defines every message in every language. In every component that needs a translation, I need the concerned object key in the state like so:

  1. getInitialState: function() {
  2. return {
  3. translation : hueApp.translation.hue.bridge
  4. }
  5. }

I can then access the translation properties in the render method:

  1. <span className="message">{t.state.translation.lookingForABridge}</span>

It works as intended. What do you think of this method? Have you done any multi lingual project with React you could share? What's not ideal is that in my i18n object, I can't write HTML, and that could be a little annoying. For example, in a string, if let's say you'd want to add just a
to break the line, it won't be interpreted as HTML in the render, you'll see the line break as text. I don't know if there's a way to interpret the string as HTML.


Learning a new language, or framework, or tool is always hard work. It gets you out of your comfort zone, you're facing a problem and you don't know the answers yet. You feel slow comparing to your usual velocity. It can force you to think differently, to adopt a different method, and that's why I think it is the beneficial. It helps you to open your mind and the next time you'll face a new problem, you'll have more experience to tackle it, different method at your dispositions and I'm convinced this approach helps you get a better developer.

When learning, there's always the theory and the practice. When starting from scratch I usually prefer to do both in parallel, because you need to understand the theory to practice, and the practice will bring questions and challenges whose answsers are found in the theory, that's why I try to learn with a concrete little side project not too big (not to get drowned), but big enough to make you face typicall chanllenges.

I liked React's organisation and focus. Everything is a component that has a defined scope, a bit like web components, which seem to gain more and more momentum in our industry. It fit nicely with my little app, but I'm wondering how this would scale in a large app. Maybe one of you has an example of large sites built with React, or know an interesting article on the subject.

Don't hesitate to let me know what you think in the comments, you certainly know more about React than I do. Again I precise that this was my first encounter with the tool, it's a beginner's point of view. I hope this (rather long) read will make you gain some time on certain aspects if you begin as well.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

Other Useful Resources

How to create an Ajax, validated form illustration

Even on some very famous websites and blogs based on the WordPress platform, such as Smashing Magazine or Webdesigner Depot for example, the comment forms are not checked prior to submission. Which means that if the user hits the submit button without actually filling any information, he is redirected to the famous error: "Error: please fill the required fields (name, email).".

Thanks to jQuery and its plugins, it is possible to change the way those forms are handled, in order to obtain slick effects, and an overall better user experience.

In this tutorial, we'll associate the validation plugin, and the form plugin, to get a contact form that is validated before submission, and submitted via ajax. Why don't you give it a try?

Read more
Retour sur Blend Web Mix 2015 illustration

Blend Web Mix, c'est la conférence Lyonnaise du Web. C'est une chance d'assister à des des conférences enrichissantes et motivantes, de rencontrer des gens intéressants, le tout dans le cadre toujours très agréable de la cité internationale. Cette année encore, l'édition a été riche en enseignements. Retour sur les conférences auxquelles j'ai assisté, et ce que j'ai pu en retirer.

Read more
Standardizing development environments with Vagrant illustration

This is the first article of a series in which we'll explain our development process industrialisation. We'll describe how we went from a team of individuals doing things together but artisanally, to a more industrial and qualitative approach. This first topic talks about how we standardized our development environments with Vagrant.

Read more
@jeremypetrequin Ok tu build spécifiquement ce fichier scss pour avoir un fichier css que tu peux charger pour ton bloc en BO donc. Merci.22 May / 14:21