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

How to better market yourself as a React developer

Usually, I stay away from topics like "personal branding". I can see the value of this concept, but a lot of the talks surrounding it are full of bla bla.

However, I've recently discovered this recording on youtube by Shawn Wang.

What I like about this talk is that you have a lot of high applicable, practical information that you may get from something a programming screencast. Especially in the first half.

I also liked that it uses a lot of examples from the React community. How guys like Wes Bos or Kent C. Dodds build their brand. Also, it gives some great tips on where to find React and Javascript side project ideas to add to your CV.

So, go ahead, give it a try:

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

How to (and how NOT to) learn REACT?

I recently had a few conversations with some readers of JS Craft about what would be a good approach for them to start learning React. But before that, before getting to the master plan of learning React, let's do a bit of reverse psychology:

How NOT to learn React

A very underrated productivity tool is the not to do list. You will often hear about things "to do", but very few will tell you about how important it is to also have a "not to do list"

So, the not to do list of getting started with React:

  1. Start to learn all of following at once: Webpack, Redux, NextJs, Mobx, React, ES6, React Router, LESS, Node, React Fiber, Lodash, and the Context API. Also don't forget about NPM, Flux, GraphQl, Relay, Axios, Styled Components, Reducers, Babel, Yarn, SASS, Flexbox and Fetch. Go for all the acronyms and technologies! They shall not overwhelm you :)!

  2. Watch screencasts series as if they were Netflix. Just go into the surface and never repeat a screencast; hey, you already saw it once, what's the propose of rewatching it; you already know how it ends

  3. Just read as much as you can and do not code at all! Learning programming is not a practical thing with clear results.

  4. Stay away from CSS. It's bad, unproductive and not useful at all for React and frontend development in general. You are a developer and CSS is just for designers.

  5. Do not make it fun! While learning, do not make cool & fun React projects like real-life examples or games. React is Work! Work should not be fun! Work is serious stuff and it should be treated likewise.

  6. Never try to branch out from a tutorial. Strictly follow the steps from it and never try to make something that it's not included in that tutorial. Do not experiment!

  7. Never try to make a clone of a real-life app like Trello or Whatups. Apps like these never contain commonly used patterns like authentification, popups or form validation.

  8. Never ever read or use somebody else's code from places like Github. Always reinvent the wheel!

How to learn React

Setting the joke aside I’ve started with React the hard way: I've read in a chaotic "order", experimented a lot, sometimes spent weeks without much progress while other times I could have had a few a-ha moments in a single evening. My learning was pretty much self-guided, with no one to show me a simpler, or a faster way.

Maybe the biggest problem when you start learning React is all of the "things" from the React Ecosystem. All the libraries, acronyms and the flashy words. So let's make a basic fundamentals roadmap to get you started:

-> STEP 1: Javascript & basic ES6

Beside geting an intro to ES6, also, invest a few hours into NPM and Javascript Modules. Later on, knowing some basic ES6, will allow you to separate what is particular to React and what is ES6.

-> STEP 2: Learn Basic React

Start to read about and play with React. Don't overcomplicate the project's setup phase. Ditch Webpack for now and use create-reat-app (we have a short tutorial about it here) or the super nice codesandbox.

Be sure to get a good grip on fundamental things like components, properties, setState, user events, the component lifecycle and working with forms.

For now, just ignore things like Redux, React Router or Webpack.

Also if you don't like a tutorial/book /screencast series just drop it. Find something that resonates with your style of learning.

-> STEP 3: Build small projects

Things like a register form, a tic-tac-toe game, shopping cart, a Rock Paper Scissors game, multi-step forms, edit cancel inputs. Take a tutorial and add new functionality to its examples.

Here, to get you started, this is how you build a very basic calculator app in React:

Now try to add new operations like multiply and divide, validation, errors and so on.

-> STEP 4: Fetching HTTP data

Axios is a great tool working with HTTP request in React. While you are at it read a bit about ES6 promises and async-await.

The following steps can be tackled in any order you prefer:

-> STEP 5: React Router

Learn about React Router. Be sure to get the basic routing, URL prams, authentification & protecting routes and navigation events.

-> STEP 6: State management - Redux or Mobx

Even if simple state management can be done now via the React Context API (tutorials here and here) you will need to know how to manage the state of more complex apps with Redux or Mobx.

-> STEP 7: Learn CSS

If you already have a basic understanding of it, just skip this step. You don’t need to be a super expert in CSS, but a good understanding of CSS will add a lot of extra productivity to your skills.

-> STEP 8: NODE JS

If you don't have any experience, it may be also a very good idea to learn a bit about what happens on the backend with Node or any other simple Backend Language. Having a full-stack overview will help you a lot.

And by now you should have a decent overview & productivity level with React. Now you can move to the more fine-tuning stuff like:

  • optimizing the build process with Webpack
  • investing some time in reading about the Best Practices in React
  • using GraphQl as an alternative to REST
  • unit testing
  • next and GatbyJs (this is what I've used to build the js-craft.io site)

Please keep in mind that all of these are based only on my personal experience, and maybe there are better ways to organize your React leaning process 🙂 But, this should be a decent enough plan to get you started.

What can React Context API do for you? Multi-language text, Modals, and Theme switchers

I am lazy, by default. Learning something new takes effort and time. So, I always start by asking “why should I learn this? How this insert here: framework, library, programing language will make my life easier?”

A few weeks ago I’ve published a tutorial and screencast about how to use the new React 1.6 context API. It seems that also some of the js-craft readers are lazy as well. In a good way, of course :). We received a few emails sounding like: “ok, this React Context is nice, but how can it benefit me in real applications? How can I put React context to work?”.

It turns out that React Context can be used as a great tool for managing “stuff” at a global level of our application. Things like - if we have modals opened or not, multi-language support, identity management or switching a theme for our site, are perfect fits for the React Context. In these types of situations, it does not make sense to go through all the trouble of setting up full state management libs like Redux or Mobx.

If this is your first encounter with the Context API in React, it may be a good idea to read first about how to use it. The official guide is here and, as said earlier, we also have a short tutorial about it.

So, let’s see in action some of the use cases for React Context:

Building a Multi-language site with React Context

Having our app or site support multiple languages is a tedious task that usually gets pushed to the bottom of the to-do list. But, for simple things like landing pages or apps that are not very text dependent, React Context can be a great tool.

Below you have a codesandbox with our simple example:

This for sure can be improved. Please keep in mind that this is just a proof of the concept.

The core component here is the simple TranslatableText. It takes a dictionary as a property and, based on what it receives from the LanguageConsumer, it will show the message in the corresponding language:

const TranslatableText = props => (
  <LanguageConsumer>
    {({ language }) => props.dictionary[language]}
  </LanguageConsumer>
);

// and to create a TranslatableText
<TranslatableText dictionary={{
  french: "Bonjour, Michel!",
  english: "Hello, Michael!",
  italian: "Ciao, Michele!"
}}/>

Of course any of this will not work if we do not have in place a React Context mechanism. First, we will create the building blocks - the LanguageContext and the LanguageConsumer:

const LanguageContext = React.createContext();

const LanguageConsumer = LanguageContext.Consumer;

Having them created, we can now make the LanguageProvider. It is a standard React component, that stores the current language of the App and a method to update this language:

  class LanguageProvider extends React.Component {
    state = { language: "french” };

    updateLanguage = e => this.setState({ language: e.target.value });

    render() {
      return (
        <LanguageContext.Provider value={{
          language: this.state.language,
          updateLanguage: this.updateLanguage
        }}>
          {this.props.children}
        </LanguageContext.Provider>
    );}
}

It will wrap the whole app so it can expose the language and the changeLanguage method to any descendant tag via the LanguageConsumer:

const App = () => (
  <LanguageProvider>
    <div>
      //...
    </div>
  </LanguageProvider>
);

And now we can trigger the updateLanguage in the header:

const Header = () => {
  return (<LanguageConsumer>
    {({ updateLanguage }) => (
      <header> see this site in:
        <select onChange={updateLanguage}>
          <option value="french">french</option>
          <option value="english">english</option>
          <option value="italian">italian</option>
        </select>
      </header>
    )}
    </LanguageConsumer>);
};

Managing Modals with React Context

At the first glance having a modal appearing in a React application, it’s an easy win. It should not need any React Context fancy stuff. But, when your app will start to grow bigger and more complex, and the modal state is all over the place, then the React Context starts to make sense.

Below you can see the an example of how to use a React Context to manage Modals:

All the magic takes place into the Provider component. It will decide if we should have a modal opened and will use the Modal wrapper component to display the ModalContent.

class Provider extends React.Component {

  showModal = (content, props = {}) => {
    this.setState({
      Content,
      props
    });
  };

  hideModal = () =>
    this.setState({
      content: null,
      props: {}
  });

  state = {
    content: null,
    props: {},
    showModal: this.showModal,
    hideModal: this.hideModal
  };

  render() {
    const ModalContent = this.state.content;
    return (
      <ModalContext.Provider value={this.state}>
        {this.props.children}
        {ModalContent ? <Modal content={ModalContent} /> : ""}
      </ModalContext.Provider>
    );
  }
}

One of the nice parts is that the "design" of this system allows us to fully customize what gets into the content of the Modal. When you trigger the creation of a modal you will need to pass in a React component. This can be any HTML we need, like a simple text, an image or anything else.

const TextModalContent = () => (
  <div>
    <h1>Text modal</h1>
    <p>Some next here !</p>
    <CloseButton />
  </div>
);

const ImageModalContent = () => (
  <div>
    <img src="https://media.makeameme.org/created/take-a-break-09utnz.jpg" />
    <CloseButton />
  </div>
);

//...
<button onClick={() => showModal(TextModalContent)}>Open Modal</button>,
<button onClick={() => showModal(ImageModalContent)}>
Open Image Modal</button>

The Modal component only serves as a wrapper for some CSS classes, in order to make something to look like a modal.

const Modal = props => {
  const Content = props.content;
  return (
    <div className="modal">
      <div className="modal-content">
        <Content />
      </div>
    </div>
  );
};

For sure you can improve this example by having things like callback functions for the modal’s modals’ ok-cancel buttons, or parameters that could customize some modal templates. But, for beginning, I think it's a good start.

You can read here a nice article about React Context and Modals. I’ve used it as an inspiration for this article 🙂

Making a Theme switcher with React Context

I’ve always liked how apps like Twitter or Feedly give you the opportunity to select if you want to change a light or dark color scheme.

And guess what!? It’s quite easy to implement this with the React Context:

This is the most straightforward one out of these three examples. First, we will need to define two CSS classes that will contain the rules for how the app will change based on the selected theme:

.day {
  color: black;
  background-color: white;
}

.night {
  color: #5692e6;
  background-color: #142b41;
}

Following this, the provider will expose the CSS’ class name and a method to toggle it:

  class TProvider extends React.Component {
    toggleTheme = evt => {
      this.setState({ theme: evt.target.checked ? "night" : "day" });
    };

    state = {
      theme: "night",
      toggleTheme: this.toggleTheme
    };
    //..
}

The toggleTheme method will be called when the user changes the status of the Theme slider:

class Slider extends React.Component {
  render() {
    return (
      <label className="switch">
        <TConsumer>
          {({ toggleTheme, theme }) => (
            <input 
              onChange={toggleTheme}
              type="checkbox"
              checked={theme === "night"}
            />)}
        </TConsumer>
//...

And given the fact that theme state value of the Context Provider is set as the className of the main div of our app, this will also update how the app looks like:

  const App = () => (
    <TProvider>
      <TConsumer>
        {({ theme }) => (
          <div className={theme}>
          <h1>React Context</h1>
//...

For sure you can also find other practical applications for React Context. However, keep in mind that React Context is a feasible solution mostly for lightweight cases. React context it’s not (or at least not yet) designed to be a complex state management solution. There are cases in which your app will benefit from Redux or Mobx, but for simple stuff, it does not make sense to add that extra code and you can just use the built in React Context.

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.