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

Introduction to React state and stateless components

If you have been learning React you would probably came across the state word being used all over the place. The heart of every component lies in its “state”! But … what is this state we keep hearing about?

What is the state in React?

The “state” is the sum of the things inside of a React Component that can change AFTER that component is built.

The state of a React component is often used with a comparison to the props of that Component. Opposite to the state, the props cannot be modified once the component is created.

Let’s take the below codesandbox. Click around on some of the buttons:

It’s a Survey app made by multiple Question components. During the execution of our survey, there are two things that may change in a Question:

  • if the buttons are disabled and
  • the text of the answer status

Both changes will take place based on one check - if the user answered the question or not.

So, a question starts with state of a null answer:

class Question extends React.Component {
    state = {
        answer: null
    };
}

And, when any of the buttons are pressed, we will set on to the state of the component the received answer.

setAnswer = (pressedButtonText) => {
    this.setState({
        answer: pressedButtonText
    });
};

//…
<button onClick={this.setAnswer.bind(this, "YES")}> YES </button>
<button onClick={this.setAnswer.bind(this, "NO")}> NO </button>

Please pay attention to the fact that, besides the initial declaration, you should always use this.setState(...) in order to change the value of the state.

And finally, the change in our state will determine the component visuals to be updated:

render() {
    // this will update the answer text
    {this.state.answer ? 
        <i>You replied with {this.state.answer} to this question.</i>: 
        <i>Please reply</i>}

    // this will update the enabled/disabled status of the buttons
    <button
        disabled={this.state.answer}
        onClick={this.setAnswer.bind(this, "YES")}
    >YES</button>
    <button
        disabled={this.state.answer}
        onClick={this.setAnswer.bind(this, "NO")}
    >NO</button>
}

On the other side, the properties will keep their value constant throughout the execution of the Survey.

You can see also in the screencast about building a React Edit Cancel Text Input component how to use the react state in order to control the way a React component behaves.

Where to Initialize State in React

There are three places where you can initialize the state of a React Component.

1. Initialize the State as a class property

This is the approach we used for our Survey example. Just set the state directly inside the Component as a class property:

class MyComponent extends React.Component {
    state = {
        isLoading: false,
        totalScore: 10 
    };
}

Setting the initial state as a class property requires the least amount of codeing?. Usually, this is the preferred way of initializing the state.

2. Initialize the State via a Constructor

Initializing state inside the constructor looks like this:

    class MyComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                isLoading: false,
                totalScore: 10 
            };
    }
}

The constructor is the first method to be called when the component class is created. So, it’s the right place to initialize everything, including the state.

It is very important, when you use a constructor, to make sure that you call the parent class’ constructor: the super(props) line.

You can check this article if you want a more in-depth comparison. whether you should use a constructor or not. But the short answer is that you don’t need a constructor.

3. Initialize the React State using the getInitialState method

This way of initializing the state will only work with the when using the React.createClass from the older ES5 syntax.

var MyComponent = React.createClass({
    getInitialState() {
        return {
            isLoading: false,
            totalScore: 10 
        };
    }
});

Unless you are bound to using ES5, try to avoid it.

Stateless components

As a complementary concept to the React state is the stateless components. They are also called “Presentation only” components or “Dumb components” (maybe this is not the most polite way of referring to them).

When the sole purpose of a React Component is just to show some information, and, if that component does not change, then it means that it is a React stateless component. It does not have a state.

For example, if the scope of a Question Component is just to show the question text, then it could be written like this:

class Question extends React.Component {
    render() {
        return (
            <div className="question" style={{ borderColor: this.props.color }}>
                <b>{this.props.question}</b>
            </div>
        );
    }
}

// and to make a Question
<Question
    color="red"
    question="Was Mike Tyson one of the greatest boxers?"
/>

Furthermore, starting from React .14 we have a simpler way to write Stateless components. We can use the ES6 arrow functions and just say:

const  Question = (props)=> {
    return (
        
{props.question}
) )

Or, if we want to take advantage of the JavaScript Named Params Destructuring and the fact that the arrow functions are returning the last used statement, then we can write:

```javascript
const Question = {color, question} =>(<div className="question" style={{ borderColor: color }}>
<b>{question}</b>
</div>)



If we take a look, we managed to reduce the code of our function from 7 lines to 3. Maybe not always fewer lines of code is the same thing as a more readable code, but still, a 50% decrease in the code lines is an improvement.

Wrapping it up, I hope this small article made React state a bit more clear. As the main takeaways:
    - use the state object to control the things that will change AFTER that component is built
    - always use setState to modify the state of React Components
    - if a component is present only present information, and has no logic, then to make it a stateless component

The 7 Most Common Mistakes that beginner React Developers Make

Recently I had to hold a React workshop for some developers from a company I am working with. Some of them were juniors and others where experienced backend devs, but, to my surprise, there were some common issue patterns that kept repeating for both categories. So, I’ve decided to make a list of these common mistakes hoping it will save you some moments of frustrations when you first start to learn React:

1. Anything that it is state changing should be done via the setState method

Maybe this is an old subject, and for seasoned React developers it may be obvious but, it is still one of the most encountered issues when starting with React.

So, never ever try to do something like this:

this.state.someValue = 10

It will not work, the view will not be updated and the worst thing is that we will not get any error on the console telling us that we did something wrong.

As a general rule of thumb, always use setState when you want to change something in the state. This will ensure that the render() method is triggered and the view is updated.

this.setState({someValue:10})

2. The setState method is async

Speaking of state. - the state in React is async. It means that if we call setState, we don't have a guarantee that, when the next line is executed, the change actually took place. This can catch off guard even developers that are using React for quite some time.

If we try to use setState multiple times in the same function or code block, we may get into some strange behavior. For example, on a click handler, if we have some code like this:

doStuff = () => {
this.setState({ foo: this.state.foo + 1 });
    if (this.state.foo > 7) {
      this.setState({ bar: 20 });
    }
 }

If you use this code you will see that bar becomes 20 only when foo is 9. This is the result of the async nature of setState. When the if statement is evaluated, the setState will not have enough time to make the changes. So when foo is 8 the if statement is still evaluated as false.

In order to fix this let’s take a look at the setState documentation. We will discover a mysterious callback function that will ensure the fact that some code will be run only after setState actually makes the change. So, we can try something like this:

doStuff = () => {
   this.setState({ foo: this.state.foo + 1 }, () => {
     if (this.state.foo > 7) {
       this.setState({ bar: 20 });
     }
   });
};

And below you can see the previous example, but this time implemented with the callback function.

3. Sending props as Strings instead of Numbers

If you used to write a lot of pure HTML, you may find it natural to write something like:

<MyComponent value="2" />

However, it will send the value prop to MyComponent as a String. So, if you need it as a number, you will have to use something like parseInt. Or do it the React way: use curly brackets when sending it:

<MyComponent value={2} />

It will also work if you have to send some other javascript entities like objects or arrays:

As an alternative, you can use react props-types to define what data type a React property should be. Please note that props-type now has its own npm package.

4. Not using the right versions of what an example or a tutorial is using.

This was not directly related to the workshop, but it’s in the same category. I recently had one reader of js-craft.io emailing me and saying he is trying to follow the React API example, but for some reason, he gets some exceptions, even if the code is exactly the same. Well, it turned out that he opened an older project and tried to use the React 1.6 Context API. Meanwhile, in his package.json ,the React version was below 1.6. So, remember to check the versions from package.json 🙂 !

The following ones are still examples of what React beginners do (and from time to time we all make them), but fortunately, they are way easier to catch as they come with some errors or warnings in the console.

5. Using class instead of className

In React, if you want to assign a CSS class name to a component don’t try to do something like:

<h1 class="css-class-for-title”>Some title here</h1>

In React-JSX it will fail, as the class keyword by ES6.

Instead use className:

<h1 className="css-class-for-title”>Some title here</h1>

6. Not starting a component name with a capital letter

This one is pretty self explanatory. If you will write something like:

class myApp extends React.Component {
}

You will get a nice and beautiful: If you meant to render a React component, start its name with an uppercase letter. error. So, React components start only with a capital letter.

7. Trying to use objects with curly braces - children not accepted as object

This happens mostly to debug. When you want to show the contents of an object in React don’t expect that curly brackets in React will work similar to the standard console.log. If you will try to use curly brackets with an object you will get an error:

render() { 
  let objToPrint = {
    name:"Bob", 
    age: 5 
  } 
  return (<div>{objToPrint}</div>); 
}

If you really have to print the contents of that object then go for JSON.stringify:

render() { 
  let objToPrint = { 
    name:"Bob", 
    age: 5 
  } 
  return (<div>{JSON.stringify(objToPrint)}</div>); 
}

And as a closing thought, even if it’s not an actual mistake: try to break down and reuse components as much as possible. It's easy to write bloated components when you first start using React. Small classes/modules/whatever are easier to understand, test, and maintain, and the same is true for React components.

My mistake, when starting out with React, was under estimating just how small my components should be. Of course, the exact size will depend upon many different factors but, in general, my advice would be to make your components significantly smaller than you think they need to be.

Introduction to using GraphQl in React with Apollo

What is GraphQl and why should I be interested in it?
In a nutshell, we can see GraphQL as a syntax that describes the data you get, usually from a backend API. It was created by Facebook and in most cases, it provides good solutions to REST API's problems.

For this tutorial, the scope is to get up and running with a React application that uses Apollo to interact with a GraphQl endpoint. We will go intro more details in other articles, but for now the idea is to understand and "feel" the general workflow in GraphQl.

We will build a very simple movie application, that will interact with some data from a GraphQl endpoint. You can see it in the below image.

Installing GraphQl and Apollo

To get started we will need to add bunch of libraries to our project. If you want you can use create-react-app. Create a React app then open up a console and type:

npm i -save react-apollo graphql-tag apollo-boost

As very short run through:

  • react-apollo is the connector that links React to GraphQl. An alternative to it is Relayjs.
  • graphql-tag will be useful to write the GraphQl queries
  • and from the apollo-boost we will use the ApolloClient as the main bridge to the GraphQl endpoint

From a code perspective, we will first need to create an instance of the ApolloClient client. The ApolloClient will need the uri of the GraphQl endpoint.

import ApolloClient from "apollo-boost"

//...
const client = new ApolloClient({
  uri: "https://r9v94p7kqn.lp.gql.zone/graphql"
})

After having the ApolloClient instance ready, we will then wrap the main app content with an ApolloProvider:

import { ApolloProvider} from "react-apollo"
//...
class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
          <Movies />
      </ApolloProvider>
    );
  }
}

Seting up a Javascript - GrapQl endpoint

You may have noticed the uri: "https://r9v94p7kqn.lp.gql.zone/graphql" from the ApolloClient constructor. If you leave out the /graphql and visit the link https://r9v94p7kqn.lp.gql.zone you will see the graphql launchpad that contains our endpoint.

Without going too deep into details our endpoint has a

  1. a schema definition that describes how a basic movie data will look like, but also what type of data the queries will return:

    // Construct a schema, using a GraphQL schema language
    const typeDefs = `
    type Query {
    allMovies: [Movie]
        movie(id: Int!): Movie
    },
    type Movie {
        id: Int
        title: String
        director: String
        actors: [String]
        poster: String
        year: Int
    }
    `;
  2. and also, a set of data + resolver functions that will be used when a query takes place:

var moviesData = [
    {
        id: 1,
        title: 'The Godfather',
        director: 'Francis Ford Coppola',
        actors: ['Marlon Brando', 'Al Pacino', 'James Caan'],
        poster: 'https://ia.media-imdb.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_UY268_CR3,0,182,268_AL_.jpg',
        year: 1972
      }
      //...
];

var getMovie = function(root, {id}) { 
    return moviesData.filter(m => {
        return m.id === id;
    })[0];
};

var getAllMovies = function() {
  return moviesData;
}

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    allMovies: getAllMovies,
    movie: getMovie,
  },
};

// Required: Export the GraphQL.js schema object as "schema"
export const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

In this example, we have used Javascript, but you can setup GraphQl endpoints with any major programming language. Please note, that the core data - moviesData array - should usually come from a database. We just used this static array for simplicity purposes.

Making the first GraphQl query with React - Apollo

There are multiple ways to query a GraphQl endpoint. To list the basic info of the movies we will use the Query component from react-apollo:

import { Query, ApolloProvider } from "react-apollo";
//...
const Movies = () => (
  <Query
    query={gql`
      {
        allMovies {
          id
          title
          poster
          actors
        }
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error :(</p>;
      return data.allMovies.map(movie => (
        <div className="movie">
          <h3>{movie.title}</h3>
          <p>{JSON.stringify(movie.actors)}</p>
        </div>
      ));
    }}
  </Query>
); 

Using the parameters loading, error, data that we get access to in the child function, we can control how the layout looks like when the data is still loading or when we get an error response. At this point the complete code and app looks like this:

Triggering a GraphQl query on a React UI event

But what if we wanted to trigger a query on a specific UI event, like a button click? For example, if we wanted to get the complete details for a movie when a Get all details button is pressed.

First let's extract a Movie component:

class Movie extends Component {
  getDetails = ()=> {
   // will make the GrahQl here
  }

  render() {
    return(
        <div className="movie">
          <img src={this.props.data.poster} />
          <div className="details">
            <h3>{this.props.data.title}</h3> 
            <p>{JSON.stringify(this.props.data.actors)}</p>
            <button onClick={this.getDetails}>Get all details</button>
          </div>
        </div>
    )
  }
}

//...

const Movies = () => (
    {({ loading, error, data }) => {
    //...
return data.allMovies.map((movie) => (
<Movie key={movie.id} data={movie} />
));
    }}
);

Now, to manually trigger the GraphQl Query we will need access to the ApolloClient instance in the Movie component. All the components that are descendants of the ApolloProvider can gain access to the client instance by using the withApollo() helper function:

import { Query, ApolloProvider, withApollo} from "react-apollo";
//...
class Movie extends Component {
  //...
}
Movie = withApollo(Movie)

So now we can access the ApolloClient as a property of the Movie component, and use it to trigger the query call:

class Movie extends Component {
  getDetails = ()=> {
    this.props.client.query({
      query: gql`
        {
          movie (id:${this.props.data.id}) {
            id
            title
            director
            actors
            year
          }
        }
      `,
    }).then((data) => alert(JSON.stringify(data.data.movie,null,'\t')))
  }
  //...
}

You can play with the complete app in the bellow code sandbox:

I hope you enjoyed this article and realized is quite easy to get up and running with using GraphQl in React. This is just the tip of the iceberg, but hey ... every journey begins with a single step :).

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.

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.

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).

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!