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

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

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

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

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

Audio transcript

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

react game tutorial

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

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

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

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

node -v  

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

npm install

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

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

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

npm start

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

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

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

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

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

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

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

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

npm install -g create-react-app

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

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

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

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

cd my-first-react-app

And to have it running now just type:

npm start

You should now see something like the picture below:

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

Why should you have a side project as a javascript developer

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

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

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

Sideprojects as a learning tool

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

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

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

Passing the job interview with a sideproject

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

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

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

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

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

So go ahead, build something!

How to build a React Edit Cancel Text Input component

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Build a password strength checker with zxcvbn and React

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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