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

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!