Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Your first application with React and Mobx 4

If you are in the React world there are some pretty high chances you may have heard about Mobx. Mobx is a lightweight and easy to learn state management library developed by Michel Weststrate.

Its 4th version was released a few weeks ago and it comes with a lot of new cool features.

We will start our journey in the Mobx world by building a small project: a simple Table Manager that will manage the salary data for some employees. 

From a feature point of view, our app will be able to :

  • render a list of employees in a table (an employee is made of a name & salary)
  • add a new employee
  • clear the list of employees  
  • calculate the total cost of salaries
  • show how many employees earn more than 500$ per day 

And maybe, the most important "feature" will be the fact that we will do everything by managing our app state with Mobx. 

The basic setup of the project

We will start with the following basic setup. We just have some very basic components that mostly return some divs with some basic HTML tags.  

The basic component architecture looks like this:

Adding a store to our application

In this phase, our app is not fueled by any data. There are just some empty components. The initial data for our app will be an array of employee objects with a name and a daily salary

employeesList = [
    {name: "John Doe", salary: 150},
    //... 
]

This data will have to be used in multiple components:
  - in the Table (in order to list the employees)
  - and in the Controls component, for adding a new employee or clearing the list

Given the fact that sending data and callbacks via props is not the most scalable solution for the core data of the app we could try to put together an appStore object that will encapsulate and manage this core data. This way, initially, we will have just to pass this appStore.

class Store {
  employeesList = [
    {name: "John Doe", salary: 150},
    {name: "Richard Roe", salary: 225},
  ]
}
const appStore = new Store()

Having the AppStore created we can send it now we can now send it to the main components:

<Controls store={appStore} />
<Table store={appStore} />

And now we can list the contacts in the Table component:

class Dashboard extends Component {
  render() {
    const {store} = this.props
    return <div className="dashboard">
      {store.contactsList.map((c, i) =>
        <Contact 
          key={i} 
          name={c.name}
          email={c.email}
        />
      )}
    </div>
  }
}

So far so good. However, if we try to add a new employee by pushing a new item into the appStore.employeesList or if we try to clear the list:

class Controls extends Component {
  addEmployee = ()=> {
    const name = prompt("The name:")
    const salary = prompt("The salary:")
    this.props.store.employeesList.push({name, email})
    // ERROR !!! this will not update the view 
  }

  clearList = ()=> {
    this.props.store.employeesList = []
    // ERROR !!! this will not update the view 
  }

  render() {
    return(<div className="controls">
      <button onClick=>clear table</button>
      <button>add record</button>
    </div>)
  }
}

We will not have any update of the view, even if things seem to work as they should:

You can also try to do a console log of the data and you will see that it all seems to be ok. The problem consists of the fact that React does not gets notified when the object was changed so it can start the rerendering. 

Installing Mobx 

Mobx deals with exactly these types of situations. It is a perfect tool for notifying React when things have changed in its data state.  

But first, let's first add it to our application. The fastest way to install Mobx is by using NPM. Besides mobx we will also add mobx-react that we will use to glue together mobx and react. 

So, open up a console and type: 

npm install -save mobx mobx-react

With the instalation complete we will add some new imports to our App.js:

import {decorate, observable} from "mobx"
import {observer} from "mobx-react"

Introducing the Mobx basics: observers - observables

Very in a nutshell mobx works on the observable - observer flow. You declare some data to be observable and when that data changes all the observers that are using that data will be notified. 

In our example, the data that is changed is the employeesList. In mobx there are a few different alternatives to declare some data as observable. We will use the newest one, as it is, in my opinion, the most elegant and easy to use. It was added in Mobx4 and it is something like this:

class Store {
  //...
}

decorate(Store, {
  employeesList: observable
})

const appStore = new Store()

Now, to complete the flow, we will have to make the Table component to be an observer:

class Table extends Component {
  //...
}
Table = observer(Table)

And with these new changes we should have everthing working:

Using actions and configure-enforceActions in Mobx

Even though it all seems to be working ok we are breaking a very important rule of Mobx: state data should be modified only through actions. This will make the code more scalable and improve the data flow management. 

Mobx even provides a mechanism for making sure this rule is respected. If we will add the following two lines to the app:

import {configure} from "mobx"
configure({enforceActions: true})

When we will press the clear employeesList button or when we will add a new employee, we will end up the this: Error: [mobx] Since strict-mode is enabled, changing observed observable values outside actions is not allowed:

This is happening because we are trying to change the state outside of a function. To fix this we will first have to import the action, add two new functions to the store and declare them as actions:

import {action} from "mobx"

class Store {
  //...
  clearList() {
    this.employeesList = []
  }

  pushEmployee(e) {
    this.employeesList.push(e)
  }
}

decorate(Store, {
  clearList: action,
  pushEmployee: action
})

Having the actions, we can now replace the unsafe data manipulation with the calls to these actions:

class Controls extends Component {
  addEmployee = ()=> {
    const name = prompt("The name:")
    const salary = parseInt(prompt("The salary:"), 10)
    this.props.store.pushEmployee({name, salary})
  }

  clearList = ()=> {
    this.props.store.clearList()
  }
  //...
}

By now everything should be back to normal and our data management is now completely encapsulated in the Mobx store: 

So, to sum it up:

  • where needed, make your data observable
  • set observers to the components that are using the observable data
  • only change observable via actions

I hope you like this tutorial, and if you would like to see more examples of Mobx or React you can always subscribe to my email list

Using computed values in Mobx 

Another core concept of Mobx is, the computed values. Basically, we can define computed values as data that is generated by doing calculations on the core data. You can see them as the data generated by formulas in Excel. 

One perfect example could be the one of the total sum of individual salaries. 

To create a computed value, we will import the computed concept and add a new property getter into the Mobx store. The new property will store the total sum of salaries.

import {computed} from "mobx"
class Store {
  //...
  get totalSum() {
    let sum = 0
    this.employeesList.map( e => sum = sum + e.salary)
    return sum
  }
}
decorate(Store, {
  //...
  totalSum: computed
})

Finally, we will just need to add a footer to our table and use the computed value.

class Table extends Component {
  render() {
    const {store} = this.props
    return(<table>
      //...
      <tfoot>
        <tr>
          <td>TOTAL:</td>
          <td>{store.totalSum}</td>
        </tr>
      </tfoot>
    </table>)
  }
}

This sum will also be updated when we clear or add to the employeesList. 

A golden rule of Mobx is to store the minimum required amount of data and compute as much as possible. This will give you good performance and re-rendering speed.

For example, another possible use case of Mobx computed values is counting & keeping track of how many records meet a specific condition. Let's say that we want to add an app footer where we will display the total number of the employees that earn more than 500$ per day. 

Similar to the totalSum, also, in this case, we will add a computed value, only that now we will use the length of an array filter:

class Store {
  //...
  get highEarnersCount () {
    return this.employeesList.filter( e => e.salary > 500).length
  }
}

To display the result in the Table component we will add a new div:

class Table extends Component {
  render() {
    return (<div>
      //...
      <div className="fade">
        You have <u>{store.highEarnersCount} team members </u>that earn more that 500$/day.
      </div>
    </div>)
  }
}

This should be it. You can play with the full example in the below codesandbox:

I can't stress enough the importance of computed values in Mobx. They are very useful in a lot of scenarios. You can also see a great example in the egghead course of Michel Weststrate, the creator of Mobx.  

There are a lot of Mobx features that were not covered in this tutorial. Things like providers, making HTTP calls or using Mobx with a router, just to name a few. But you've got the fundamentals by now: action -> observable -> observer -> React rerender. The Mobx docs are well-written and contain a lot of best practices.  

React context API Tutorial

Hello and welcome! A few days ago React 16.3 was released and alongside other things it also delivered a new React context API. The scope of this tutorial it will be to see in action this new React context API.

Have you ever passed a property to a React component for no other reason but just to be able to pass it down to a child of that component? Well, this is exactly what the new React Context API tries to fix.

The problem?

For example in the example below:

  • we have some data, namely a number with the value of 10
  • we need the data in the Red component and also in the Green one
  • the Green component is a child of the Blue component that is a child of the Red component
  • so, most probably, we will need to send the data from the Red component to the Blue one just to be able to send it to the Green one

In this point our code would look something like this:

const Green = (props) => (
  <div className="green">{props.number}</div>
)
const Blue = (props) => (
  <div className="blue">
    <Green number={props.number} />
  </div>
)

class Red extends Component {
  state = {
    number : 10
  }
  render() {
    return  <div className="red">
      {this.state.number}
      <Blue number={this.state.number} />
    </div>
  }
}

We have to send the data to the Blue component only to “drill” it down to the Green component. And this is a simple case. Imagine what will happen if we have ten levels of parent-child React components.

Till React 16.3 the standard solution to problems like this one was Redux or Mobx or any other library that deals with state management. But now, we have the solution embedded into React.

The solution: state management with React Context?

What React Context is allowing us to do is to define data stores and access them where they are needed. We don’t have to pass down data through properties any more. With React Context we can define something like an “application global state” and use that data where needed.

How to use React Context ?

There are two main steps to setup the React context into your application :

  1. setup a context provider & define the data you want to store
  2. use a context consumer where ever you need the data from the store

In order to make the context provider we will need to make a context via React.createContext. We will call our context AppContext:

const AppContext = React.createContext()

The newly created AppContext will be used to build a context provider component. This provider will store, in its state, the data we need and it will wrap all of the content of the Red component:

class AppProvider extends Component {
  state = {
    number : 10,
  }
render() {
    return <AppContext.Provider value={this.state}>
    </AppContext.Provider>
  }
}

//...

class Red extends Component {
  render() {
    return  <AppProvider> 
        <div className="red">
          <Blue />
        </div>
    </AppProvider>
  }
}

Long story short: by wrapping everything in this AppProvider we can easily inject the data from the value attribute where needed. Given the fact that AppProvider will be used as a wrapper component it’s important to use the {this.props.children} in the render method.

Now, with the provider installed if we want to access some data from the provider we can easily use the context consumer.

<AppContext.Consumer>
      {(context) => context.number}
</AppContext.Consumer>

All the data that we added to the value property of AppContext.Provider is now made available by the context parameter of the arrow function.

At this point our code will look something this:

const AppContext = React.createContext()
class AppProvider extends Component {
  state = {
    number : 10
  }
render() {
    return <AppContext.Provider value={this.state}>
      {this.props.children}
    </AppContext.Provider>
  }
}
const Green = () => (
  <div className="green">
      <AppContext.Consumer>
        {(context) => context.number}
      </AppContext.Consumer>
  </div>
)
const Blue = () => (
  <div className="blue">
    <Green />
  </div>
)

class Red extends Component {
  render() {
    return  <AppProvider> 
        <div className="red">
          <AppContext.Consumer>
            {(context) => context.number}
          </AppContext.Consumer>
          <Blue />
        </div>
    </AppProvider>
  }
}

Please note that we are not anymore passing down the number property to the Blue component or the Green one anymore. All of this data is now handled by the React Context mechanism.

Using actions and modifying data in the React Context

Unless you are working on a very basic app you will need a way to update/change the data that comes from the React Context. The minimal example can be a button that will increment the number from our data.

We will need something that is the alternative from the Mobx or Redux actions.

This is quite easy to achieve. What we will to do is to define a function on the state of the AppProvider context, and do the required updates onto the state data.

class AppProvider extends Component {
 state = {
    number : 10,
    inc: () => {
      this.setState({number: this.state.number + 1})
    }
  }
  //...
}

Having the action defined we can use it through a AppContext.Consumer and call it in a onClick event:

const Blue = () => (
  <div className="blue">
    <AppContext.Consumer>
        {(context) => <button onClick={context.inc}>INC</button>}
      </AppContext.Consumer>
    <Green />
  </div>
)

Our final code will now look something like this :

import React, { Component } from 'react'
const AppContext = React.createContext()
class AppProvider extends Component {
 state = {
    number : 10,
    inc: () => {
      this.setState({number: this.state.number + 1})
    }
  }
 render() {
    return <AppContext.Provider value={this.state}>
      {this.props.children}
    </AppContext.Provider>
  }
}
const Green = () => (
  <div className="green">
     <AppContext.Consumer>
        {(context) => context.number}
      </AppContext.Consumer>
  </div>
)
const Blue = () => (
  <div className="blue">
    <AppContext.Consumer>
        {(context) => <button onClick={context.inc}>INC</button>}
      </AppContext.Consumer>
    <Green />
  </div>
)

Still in its early phase React 16.3 Context API can be used as an alternative to the classic state management alternative if your sole purpose of using a state management library is avoiding prop drilling.

I hope you found this article helpful! Let me know if there are other things you’re would want to learn in the realm of React, Mobx and Javascript.

The 10 min ES6 course for the beginner React Developer

The famous 80–20 Pareto principle is also true when it comes to the learning React & ES6 relationship. ES6 came with more that 75 new features, but from what I’ve seen, I found myself needing less than 20% of them in more that 80% of the cases.

note : just to avoid any confusions and without going into very geeky stuff JavaScript is the same thing as ECMAScript (or ES). ES6 = ES5 + some new features, so both ES6 and ES5 are Javascript. The main difference lies in the set of supported features.

For me it was quite confusing two years ago when I first moved from good old Angular 1, and “pure” ES5 Javascript, to React and seeing in some tutorials things like arrow functions or destructor statements. It was not clear, what was from React and what from ES6.

Actually, for the first week or so, I was almost sure that you could write something like {name} only in React.

Not even by far this is intended to be a complete run-through of all of the new features. It is only the “stuff” from ES6 that I’ve seen used in the vast majority on the React code. So … here we go:

Let and const

In the “old” Javascript (meaning ES5), to declare a variable we were using the keyword var. Given some black magic thing called Javascript hoisting we could use a variable before declaring it.

// ES5
console.log(myVar); // prints out undefined
var myVar = 10;

This can lead to some behavior. Not anymore. In ES6, via the let or const keywords you must explicitly declare something before using it.

// ES6
console.log(myVar) // ReferenceError myVar is not defined
let myVar = 10

As you can imagine, the difference the between const and let is that you cannot change a const after it gets its initial value.

// ES6
let x = 10
const y = 20
x = 25 // all is ok
y = 30 // TypeError: Assignment to constant variable.

No more semicolons

From ES6 both ECMAScript 6 and all the related tools perfectly support automatic semicolon insertion. As a consequence, ECMAScript 6 coders nowadays can get rid of nearly all semicolons and remove some clutter from their code.

//ES5
var theNumber = 10;
console.log(theNumber);

//ES6 - look ma’ no semicolons
let theNumber = 10
console.log(theNumber)

Not quite a life changing feature , but for sure a nice one, especially if you had at some point a love affair with things like CoffeeScript.

Arrow functions

To make a function in ES5 you will have to write something like:

// ES5
var sum = function(a, b) {
   return a + b
}

In ES6 you can fast type it by using :

// ES6
const sum = (a, b) => {return a + b}

And , if you have a very simple one line function , you can even drop the return keyword:

// ES6
const sum = (a, b) => a + b // a one line arrow function will auto return the result of last used value

Another thing to keep in mind is that arrow functions are automatically bound to their upper scope:

function DogWorldContext() {
  this.age = 0

  setInterval(function growUp() {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithStandardFunction = new DogWorldContext()
// will print Nan every second, as the growUp is a standard function it has it's own this keyword context.
function DogWorldContext() {
  this.age = 0

  setInterval(()=> {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithArrowFunction = new DogWorldContext()
// will print 1,2,3 ... every second

The arrow functions don’t have their own this. The this context becomes the parent one, in our case the DogWorldContext.

Destructor statements

To quote from developer.mozilla.org the destructor statements makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

It is quite a common case the need to extract a attribute from a object into a separate entity. Let’s say we have the following code:

// ES5; let's say this.props.user = {name: "Daniel", age : 32}
alert(this.props.user.name + " " + this.props.user.age);

So to make it easier to read we could have something like:

// ES5; let's say this.props.user = {name: "Daniel", age : 32}
var name = this.props.user.name;
var age = this.props.user.age;
alert(name + " " + age);

But with ES6 we could use destructor statements and say:

// ES6; let's say this.props.user = {name: "Daniel", age : 32}
const {name} = this.props.user
const {age} = this.props.user
alert(name + " " + age)

Or with just one line:

// ES6; let's say this.props.user = {name: "Daniel", age : 32}
const {name, age} = this.props.user
alert(name + " " + age)

Object Literals

Somehow in the same idea we have the Object Literals. They allow us to define key-value pairs with less code.

// ES5
str = "HELLO"
number = 20
obj = {
   str: str,
   number: number
}

In E6 this can be easy translate into:

// ES6
str = "HELLO"
number = 20
obj = { str, number} // will make obj = {str: "HELLO", number: 20}

Classes, constructors and methods

We did not have class as a keyword in the “old Javascript”. So, in order to create a simple Dog class, you could make a workaround like this one:

// ES5
function Dog(name, weight){
  this.name = name;
  this.weight = weight;
}

Dog.prototype.speak = function(){
    alert("Woof, woof … my name is: " + this.name);
};

// Instantiate new objects with ‘new’
var dog = new Dog("Spike", 25);

// Invoke methods like this
dog.speak(); // alerts “Woof, woof … my name is: Spike”

You could also define a base object, and other approaches, but the bottom line was that you did not have classes “out of the box”. So meet the ES6 classes and objects:

//ES6
class Dog {
   constructor(name, weight) {
      this.name = name
      this.weight = weight
   }
   speak() {
     alert("Woof, woof … my name is: " + this.name)
   }
}
const dog = new Dog("Spike", 25)
dog.speak()

Class inheritance and React

Like in the case of Classes, in ES5 you could achieve the inheritance mechanism by doing some workarounds. But we have the extends keyword in ES6.

// ES6 
class Chihuahua extends Dog {
    shaking() {
        alert("look at me ! I’m shaking !")
    }
}

const miniDog = new Chihuahua("Mini Spike", 1)
miniDog.shaking() // I have my own methods
miniDog.speak() // but I’ve also inherited the ones from my upper classes

Also like in the case of the class keyword, extends is only a sugar syntax, but is quite useful in the React code, as it let us move from a code like this :

var Greeting = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

to a more clear version like:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Also keep in mind that if you use extends to define your React components the getInitialState() method is replaced with just a simple this.sate = … statement in the constructor of the class. You can see more about this here.

Filter

Let’s say we have the following array.

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

If you would want to create a new array only with the values that are greater than 10, in ES5 circumstances you would need a for loop, or something similar (eg: see the each() from jQuery).

Well, in ES6, we can use the filter function to go through all the values from the array and keep only the ones that meet the requirements of a function.

//ES6

const notDigits = numbers.filter( function(value) {return value > 9})
console.log(notDigits) // prints out [20,90,22,33]

// or using arrow functions
const notDigits1 = numbers.filter( (value) =>  {return value > 9}
// and we can alos use the default return or the  arrow functions
const notDigits2 = numbers.filter( (value) =>   value > 9 )

.. and Map

Even if it’s from the “old” ES5, map is one of the most underused functions of Javascript. All the time you need to loop through a array , you can use map.

Let say we have the same array as in the previous example.

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

If we just want to display the array just use map:

numbers.map( (n) => console.log(n))
// and you also have a second parameter, the index
numbers.map( (n, index) => console.log(n + ' is the ' + index + ' value from the array ') )
// or if we want to generate a second array by maping 
const double= numbers.map( (n) => n*2 )

You will see map(), over and over in React, all the time we will need to show a list of items:

render() {
    return(
  this.props.items.map( (item, key) =>  <p key={key}>{item}</p>
  )
} 

So, these are the most common ES6 features that I use when writing React code. Disclaimer: the list is highly biased and subjective :). In no way it was intended to diminish the usefulness of other ES6 features. As said earlier, there are many others ES6 that are not covered here, but these concepts should allow you to easily upgrade from ES5 React to the new ES6 syntax and understand what comes from React and what comes from the new ES6 features. Cheers and happy coding!

Build a game with React part 3 – simple animations by using setInterval and clearInterval in React JS

We will see in this final part of the series how to use React with setInterval to generate a basic animation and also how to end the running of a setInterval.

This screencast is part of a three part course. You can visit the main page of the Building a complete Rock Paper Scissors game with ReactJs course or can go directly to specific chapter:

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

Audio transcript

We achieved a lot with our application. Our game has now a basic layout, knows how to draw some random symbols and also how to show the corresponding icons for these symbols.

One thing that we could do next is to show these shuffling animations when the button is pressed. There are multiple techniques that we can use to accomplish this, but for the sake of the the example let’s pick the pure Javascript one.

In Javascript we have the two main timer functions. First we have setInterval and also we have setTimeout. For both of them the main idea is that they will execute a specific function after some time. We give them a function to execute and the delay.

The main difference between them is that setTimeout will execute the given function just once, meanwhile setInterval will execute it until canceled. Given the fact that in our example this shuffling effect is made from multiple random picks, we will use the setInterval function.      

This being said, what we should do now is go back into our code first I will take all the part that generates the random symbols and wrap it in a function, and use this function with the setInterval function. I will give a interval of 100 milliseconds, meaning that this function will be run every 100 ms until canceled. And after the save , if we press the run game button, we will see the animation in action.

Still things are not yet complete. One issue that we face now is that the animation is not stopping. For now I will just stop it manually, by refreshing the page.

We need to find a way to stop the execution of this function in a programatic way. If we go back into the documentation we will discover this clear interval function that we can use combined with a reference to a specific set interval.

Knowing this the plan will be like : we will let the function run for 40 times and after use this clear interval to cancel the execution of our function. First I will go back into the source and in here I will create a new variable called counter. This counter start with the value of 0 in a new game. Every time this function runs, the counter gets incremented.

Next we will need a reference to our interval, and I will defined here a new variable called my interval and as you can see it will point to the setInterval.

After this I will use a if statement to check if the counter had reach a level above 40 and if so I will say clearInterval of my interval.

After the save, when the page refreshes when we will run again the game we will see that our animation will stop after 40 runs.

And the final step:  we should teach the game on how to decide the winner. For this , we will introduce a new value on the state, called winner, and set it to an empty string. The decision will be taken in a new function called decideWinner and this function will be called after we clear the interval.

Given the fact that we will have to deal with state variables we will use setState and say that the winner should be this do decideWinner and out of this function will return the result of our game.

We will start by using a destructor statement to extract the value of player blue and player red out of this state.

We will start by checking player red is equal with player blue, case in which we will return a draw result.

Next we will check if the payer Red is not the winner. Begin a longer statement I will just paste this code,  but basically we just check here for every on the three cases that could make playerRed the winner and in this case we will return that player red is the winner.

And finally if we don’t have a draw and if playerRed is not the winner it’s safe to assume that playerBlue won the game.

Now all that is left to do is go inside the render method and in here in a paragraph I will display the state variable for the winner and close the paragraph.

So our game should be ready to go for a testdrive. If we run the game it will select for the red player paper, for the blue payer rock and it will tell us that the red player wins.

And this concluded our application. With this we have seen in action things like basic react components, eventHandlers or how to use Javascript timing functions with react. Thank you for watching and I hope you’ve enjoyed it. If you have questions don’t hesitate to leave a comment below and share this set of tutorials. Happy coding and see you the next time.

Build a game with React part 2 – using setState

In the second part of this tutorial we will see in action things like how to change the state of a component, will add images to our game and "teach" it how to draw some random symbols.

This screencast is part of a three part course. You can visit the main page of the Building a complete Rock Paper Scissors game with ReactJs course or can go directly to specific chapter:

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

Audio transcript

Hello and welcome back ! In the first part we added the basic parts for our game. Let’s now make our game to select some random symbol.

In order to achieve this we will need to tell the game what are all available options. I will do in the main app and add a default constructor, that just makes a super call with the default properties.

The next step will be to add a symbols filed of the this reference.It will point to an array will all of the available symbols: “rock”, “paper” and “scissors”.

We will also need a button to start the game. I will go in the main render and here add this button with the text run game.

Will will also add a run game method that initially will just have a simple console log with the text start the game.

This method will be assigned to the onClick event of the button. After the save, if I open the console you will see that every time we press the button we have this message appearing in the console.

Having this set in place , the next logical step will be to teach the game how draw a random element at the button click. Basically we will need to generate a random index and get the corresponding element out of this array.

First I will create the random index, and give it a name of index. To generate a random number I will use Math.random and will multiply this by the maximum number of symbols, in our case 3.

We will also use Math.floor to be sure that we will not get numbers like 2.5 or 1.3 or anything that is not a whole number.

And with this random index constructed we can now just console log of this dot symbols and of index.

Now if we refresh the page , when we press the button we will get a random element after that another one , another one and so on.

Let’s get these random symbols into the view now. We have to replace this static value and also this one with something like the random element generated in here.

This a perfect example to use the state of the components. First I will replace this with this dot state playerRed and also for this one I will write this dot state dot player blue.

These two state values will be set in the run game method. Given the fact that we to deal with state properties we will have to use this setState and pass it a object. Inside this object I will sat that player red equals this dot and as and index I will get this whole formula.

Will reuse exactly the same formula but this time for player blue.

Will delete the not needed code , and after we save we will see that we get an error.

This is because in here we are trying to access something from the sate and we have not yet created that state.

This is very easy to fix. I go inside the constructor and write that the state equals an empty object.

And with this set in place, if we go back in the game window can see now that every time we press the Run button we get a random symbol displayed on our screen.

Let’s go and take another look at the the final version of the game. In here we have these nice icons for the symbols and not a static text. Coming back to the code you can see that in the public folder we have this img folder, that contains the three symbol icons. All of them have a png extension.

To build this into our project we can use the background image property for the  inline style . Here I will set the URL to be the image folder plus the corresponding symbol and plus the file extension of PNG.

We will also remove the former code .. and now if we save and run the game you will see that new now also have the icons on screen.

You may wonder why this second image is rotated 180 deg. Well this is because of this css property I’ve added here and that defines that the second item that this type should have a css scale and css flip as a filter.

Build a game with React part 1 – project setup basic components inline styles

In this first part we will cover the basic project setup, meet the core components and use the inline styles to implement some of the features in our small game example.

This screencast is part of a three part course. You can visit the main page of the Building a complete Rock Paper Scissors game with ReactJs course or can go directly to specific chapter:

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

Audio transcript

Hello and welcome! My name is Daniel and I will be you instructor for this practical React JS example. Our scope for this tutorial will be to build this very simple game of rock paper scissors.

In this game we have two players. The red one and the blue one. When we press the Run game button, our game will show a shuffling animation and randomly select one of the three available elements. Based on what was selected for each player, our application will decide which of the players is the winner.

So let’s get to work then. In the starting template of this project I will run npm install. If you have not done it before, you can see in the links for this episode a guide on how to setup your environment. After the npm install is complete we can type npm start … and voila ! We should now have our application up and running.

Let’s take a look at what we currently have into the starting code: first a index.js file which only renders our application. Along side with it we have this app.css file that contains the styles for our application. Now, given the fact that this is a React JS course, we will not discuss too much about how the CSS styles where build. Only when needed we will just detail the css parts that are important for our application.

The most important part is, this app.js file that will serve as the entry point for our app. For now it only renders out a simple React component that has an empty div.

The first thing that we are gone to tackle is the creation of these two player cards. If we think a bit about them they are stateless components that are dependen on two properties: the color of the player and the symbol.

With this in mind I will go back into the code and create a new stateless component. This stateless component will be named player card. Initially our player card will be just an empty div with a className set to player-card.

This className is already defined in the app.css and ensures the basic rendering of our cards. With this stateless component created, now I can go back into the render method and in here add two new components of type player card.

And now, after we save and the page refreshes you can see on the right side the new created components.

As we said earlier our player cards are depended on two properties. They are depending on color and also on the symbol. With the new declared properties I will set the color for the first card to red and it’s symbol to paper. And for the second one I will set the color to blue and the symbol to rock.

Just to ensure that everything is ok I go back in the player card component and in here will display the symbol property. After we save we can see now the our components also have the given symbols.

You maybe are wondering why the second component has it’s text written upside down. Well this is because inside de app css we have a special rule defined for the second element with the class PlayerCard.

If we go back at our final example , each of these cards should be colored in the corresponding color. This is a great opportunity to use the inline styles of react.

For for this I will go and create a new object called style and inside it I will set the background the be equal with what we receive from the color parameter. Finally, in the returned statement of the render method I will assign the style of the div to be equal with this style object we have just created.

So, after the save you can now see that we have one card colored to red and the other one to blue.

By the end of the tutorial we will build something like this:

react game tutorial

Geting started with the code samples and create-react-app

Usually a JS Craft Screencast will provide you with two downloadable code samples: the starting version of the code and the final version - how the code should look like at the end of the screencast.

If you never did it before, first we will need to install Node. For this head on to their website, then download and install Node. It’s a good idea to pick the Recommended For Most Users version, as it is the most stable one.

After the installation is done, you can test it out in your terminal by writing:

node -v  

With Node installed on our machine we can now download a code sample, unzip it and after that open a terminal window that points to the unarchived folder. In the terminal just run :

npm install

As a shorthand you can also run just npm i. You should now get a output similar to the one below:

What npm install will do is to look into the package.json file , see the list of libraries our project needs and install them. You will see that after the install command has finished we now have a folder called node_modules containing all the required libraries and Node packages.

If no other special instructions are provided in the tutorial, we can now just run our application by using:

npm start

And this should be all that's needed to start the React examples from our site.

Install create-react-app to start a project from scratch (optional)

Many of our React screencasts examples are made by using create-react-app. This part is needed only if you want to start your own projects from scratch.

There are several ways to initiate a React project. The approach in this tutorial is based on Create-React-App and is one of the fastest ways to get you up and running with React apps as it provides a very useful set of tools.

Please note that this article is not meant to be a complete guide about this wonderful tool of Create-React-App. Instead, my goal is to provide you with a very simple setup process to start from zero our own React apps.

The installation process is the same for Windows , Mac or Linux machines.

Please be sure you have Node installed. There are instructions for doing this in the first part of this tutorial.

Node comes with NPM, a tool that allows us to easy install libraries and packages. Such a package is Create-React-App. In order to install it, go into your terminal and run:

npm install -g create-react-app

On some older Windows machines you may need to close and reopen the terminal window after you have installed create-react-app.

The -g flag comes from -global, and indicates that this package should be installed globally. This means that we can now run it from any folder. In order to test it out we can write:

create-react-app my-first-react-app

This will create a new folder called my-first-react-app containing all the files for the app. We will move inside of this folder by typing:

cd my-first-react-app

And to have it running now just type:

npm start

You should now see something like the picture below:

You can now open this project in your code editor of choice and start to play with the code. Create-react-app comes with a auto-refresh feature that will update the page as soon as you change the code. By the way, the main app file is src/app.js (index.js is used only to render out the app).

Why should you have a side project as a javascript developer

Dan Abramov completely changed his life with just 99 lines of code when he created Redux. And yes, it started out of fun as just a simple sideproject. So was the first version of Node.Js, created by Ryan Dahl. When you work on a side project, your returns are directly proportional to the value you add. The more time and effort you put in it, the more you get out.

But what can you get out of a side project? Well, quite a lot of things:

  • a great learning experience
  • a resume and a interview asset
  • last but not least: quite some fun

Sideprojects as a learning tool

Learning by doing is probably the best approach for learning React and Javascript. Opposed to the theoretical learning it allows you to get a real feel of whatever it is you’re playing around with.

One of the best strategies to learn a new framework or language is first to read and follow the tutorials or guides that usually accompanies the tool or framework. Things will work great as you have that tutorial to hold your hand at every step you make. But the real challenge starts when you start a small project by your own. In there you will meet situations that were not in the official documentation, you will start to google and dig deeper, discover new blog posts and tutorials and a new world will open before your eyes.

So the next time you learn a new framework, don't just settle for the default todo list example from the official documentation. Go deeper! For example try to build a IMDB search app, that will fetch data about your favorite movies. Having that done go for a autocomplete box, and a login mechanism. And so on. Being a self-learner is the most important skill a React developer can have.

Passing the job interview with a sideproject

Ok, we will have to admit that there are tiny changes for your side project to become a major success and you get an awesome job working full time on it. But even so it can be a great asset in your professional life.

As a junior developer there is this deadlock circle of "you will not be hired if you don't have experience" and "you can get experience only if you have a job". Sideprojects are the perfect way to break this circle. Build a side project on your own, and you will have something that will be a good substitute for the workplace experience .

Even if you are an experienced developer you still have to pass the technical interviews. But with a few sideprojects up your sleeve, you can easily slip in during a interview something like “That reminds of this thing I’ve been coding on the side”. Your interviewer will ask “what is it about?” and now the game is under your control. You know your side project probably better than any other thing you’ve worked on. And as long as the project comes off as decent and you can effectively defend your design, you’ll leave a great impression.

Also interviewers love sideprojects. They are the living proof of the two biggest assets a developer can have: passion and initiative.

So what should I do as a side project ? Since you will be spending your evenings and weekends working on this, it helps if it’s related to a topic that you are passionate about. It can be a small software application, a card game like Solitare or Blackjack or even a blog. Anything that is not a part of your day job and is out there for the world to see and use.

So go ahead, build something!

How to build a React Edit Cancel Text Input component

In a recent project, at one point we needed to build an cancel editable field. Let me show you what I mean. For example if you double click this word it will become a text input and I can set a new value for it. On the other side edit and later decide to cancel the text will remain the same. What you see in here is a jQuery plugin, so we will need a way to replicate this in react.

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

If you want you can take this as an exercise and try first to do it by your own, and later come back to check the solution.

Going to back to our stater files, what we have in this initial setup is just a basic component that shows this value from the state.

First thing will be to make this text to react to double click in order to show the edit view. This will be quite a easy win as I will just have to declare here the onDoubleClick event, bind it a function that I will call changeEditMode, and will also create this changeEditMode with just a simple console log message. After the save, if we click on the text, will get this message.

Now, the state needs to remember somehow if it's in edit mode or not. For this I will add a new variable on to the state called isInEditMode, and by default a component is not in edit mode, so this will be false.

Having this set , I can come now in the render and check is this.state.isInEditMode, and if so , will return for now just div with a empty text input that has it's default value set to this.state.value. Otherwize, will return the old stuff.

However this will not be enough, as we will also need to change this isInEditMode state variable. So when somebody does a double click, the change edit mode is called, so here, instead of the console log I will say this dot set state and isInEditMode becomes not this.state.isInEditMode.

As this will part here will become a bit more complex let's extract these two views to their own methods. Will create the renderEditView that will replace this JSX part and return it ... and also the renderDefaultView that will replace this and return it.

Now that we have a cleaner code, let's find a way to show back the default view after we go into edit mode. For this will create here a new button will have X as value and will call on click [occ] the this.changeEditMode to change toggle back the edit mode. ... and it seems to work.

And the last peace of the puzzle. Will have to update this value if the user clicks ok. So first we will need this ok button, and will add of it a onClickHandler that will call a method updateComponentValue. Let's also create this method. Inside it we will need do some state updates. First to close the edit view, by setting isInEditMode to false, but also to update this value.

To update the value, have to read the new one from here. For this particular case, is a better alternative to have refs for this input. So I will go and add here a ref of theTextInput and with this we can just go and int the updateComponentValue use this.refs the text input and value.

And this should do the trick. If I double click now, add another text and save, all seems ok, and I try to edit and cancel … then all comes back to the previous stage.

So there you have it. A nice cancel - editabile component made with React. Maybe is not the most advanced component, but I think si quite nice as a beginner example. Cheers and see you the next time.

Build a password strength checker with zxcvbn and React

Hello and Wellcome ! In this episode we are gone to tackle a very common problem. How to set secure passwords for your users. One interesting library I've discovered these days is ZXCVBN and is made by the guys from Dropbox.

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

In case you are wondering how they came up with such an, let's say, interesting name, it's the sequence made of these keys. And yes, a lot of users are setting this as a password.

Coming back, this library provides a fast way to evaluate how secure a password is.

It does not only checks for general security patterns like a minimum length or a specific number of alpha numeric characters, but also more advanced stuff like not using default words from the standard dictionary or common used passwords.

In the the starting files for this project, after the standard npm install, I will run install zxcvbn and add the dash save flag at then end. After the installation is done I can write npm start and we are good to go.

Wen we run the initial app we will see this input. I know this should be declared of type password, but for now I will just leave it to text to be able to see what we type in here.

Keep in mind that this is a controlled react input, so here you can see the corresponding state declaration, and this onChange handler that just reads the password, does a console log and updates the state.

For example now if I start to write something we will see the output in the console.

Having the library installed at the previous step I can add the import statement for it. It is quite straightforward to use this library. First I will make a new constant called evaluation ,and next use this zxcvbn object and send the password.

Finally I will console log the evaluation and delete the former console log the password.

Let's get a look at the result. If I type test as a password I will get this output. In this object we have all kinds of information. For example in the feedback we get a list of suggestions of what we can do to make our passwords more secure.

Also here we will see some statistics about how long it will take for this test password to be cracked using some different approaches.

And maybe the most important metric, is this score. This is a value ranging from 0 to 4, and is telling us the overall security level of our password.

Whit this in mind I will go and add in to the state, the score from the evaluation and the suggestions from the feedback.

We will need to show them into the view, so next I will use a destructor to retrieve the score and the suggestions from the state.

The score will be displayed here ... and will also add this unordered list as the container for the suggestions.

The suggestions are an array, so here I will take the suggestions and apply a map. The map will be manipulated by this arrow function, that will return a li element with a suggestion.

If we save this error will pop. This is happening because in here we are trying to access the suggestions but we don't have a default value for it on the state. To fix it I will initialize the suggestions to an empty array.

Finally we will also need to add in here that ... the key equals index, in order to avoid the famous React warning "each child should have a unique key". And with this we should be good to go.

For example , in here, if I type test as a password ... of course I will get 0 as a security score. Test with a capital T will only bring us a new warning , capitalization not helping too much.

With some extra repeated characters we will increase the score, but it will also tell us not to repeat words or characters.

And finally if we go completely random we will increase the security level to 3 and 4. As we said, this library uses dictionaries to identifies common words.

But the cool stuff is that we can plug in our custom words. For example, let's say upon registration someone sets his username to jscraftdaniel25. This will get a nice security score of 4.

However this is not the best idea to have as a password, as is the same with the username. To deal with this case, I can add here a extra list of words not to be set as passwords.

And with this new setup if I try to set my password to be the same as the username I will get a score of 0.

Of course we can never build the unbreakable password, but with this extra layer of security we can definalty improve things.

If you have some questions let me know in the comments below. I'm Daniel, thanks for watching and see you the next time. Cheers!