Make a Dress-up Game Using React and Sass

Screenshot by Author

In this tutorial we are making a dress up game (or character generator) using React and Sass. This tutorial and project are inspired by this article, which explains how to make a dress-up game using JavaScript, HTML, and CSS.

I would define a character generator as a user interface (UI) which allows you to choose between hairstyles, skin color, eyes, nose, mouth, and other character defining features in order to create a unique character. An example of this is South Park’s avatar generator. I would define a dress-up game as a UI which allows you to choose between articles of clothing for a static character. Dress-up games and character generators can have some overlap, since character generators can give you clothing options and dress-up games can give you some control on the character’s appearance such as hair color and hairstyle. Within this blog I will use the terms “dress-up” and “character generator” interchangeably.

The final product (so you know what you’re getting into when reading this tutorial) can be viewed here and here:

Video by Author. Video shows the implemented dress-up game playthrough.

The code discussed in this article is available in my GitHub account in a repository called React_Dressup_Game:

Get Your Images

I drew my images using Inkscape, a free and open-source vector graphics editor used to create vector images. I wanted my images to be vector graphics so that eventually I can program a way to switch colors for the images without having to save multiple versions of the same image in different colors (I haven’t figured out how to do this yet, but I know it’s possible). I exported the images as PNG files for this project, but you can try using different file formats.

The dress-up game we’re making in this tutorial will have the following changeable items: eyes, nose, ears, mouth, and clothes.

I saved each item into different layers. There’s an image for the body, and images for the different eyes, noses, ears, mouths, and clothes.

Screenshot by Author. Current visible layers(items) here are eyes3, nose3, ears3, mouth1, clothes1, and body.

The items do not overlap with each other, so we won’t have to handle overlap order (z-index) in the CSS.

File naming convention will be important for the program to work. This will have to be hard-coded.

Install NPM

Install NPM, or another package manager such as Yarn, if you don’t have one installed already. I installed the latest version of Node and NPM.

Create React Project

I created a basic React project using the Create React App which, according to reactjs.org, is the best way to start building a new single-page application in React.

Run these commands in your terminal.

npm start will run the project locally and open it in your browser. We will be overwriting the code that is currently in App.js, which is where the main logic is located.

Install Sass

Sass stands for Syntactically Awesome Style Sheets. It is a CSS preprocessor, which means it’s a scripting language that extends CSS by allowing developers to write code in one language and then compile it into CSS. It adds special features such as variables, nested rules and mixins into regular CSS, making the coding process simpler and more efficient. Sass reduces repetition of CSS and therefore is time saving.

I decided to use Sass instead of CSS so to keep the code concise, because there is a lot of repeated styles for the different dress up items.

In order to use Sass in a React project, you need to install the package node-sass, which you can do using the package manager npm, or yarn.

I use npm.

After running the command, you should see node-sass in your package.json file.

NOTE: When installing node-sass without specifying a version (having installed the latest Node and NPM versions) and running the project, I got the following error:

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0.

I read in this Stack Overflow post that in order to fix this issue you need to install the latest version of node-sass before 5.0 (which is node-sass@4.14.1) I did this and the project ran without errors.

Display Images on the Screen

Create an assets folder under the /src folder. In the assets folder, create 2 folders, one for the images (which I called “img”) and another for the Sass files (which I called “scss”).

Screenshot by Author. Screenshot taken in Visual Studio Code (VSCode).

In the /scssfolder you will save a file titled style.scss (it can be any other name, but it needs the scss extension). In the /img folder, save the images for the game (the base/static body and the exchangeable items). Have a folder per item (e.g. /eyes, /clothes, /nose, etc).

Screenshot by Author. Screenshot taken in Visual Studio Code (VSCode).

We are displaying the images by using the CSS property background-image. We define div tags in the code with a class name corresponding to the general item (e.g. eyes), and an id corresponding to an specific item (e.g. eyes1) which will be switched based on the user’s input. This is how we will change the specific items shown.

If we replace the code present in App.js with the following code:

And we add the following to style.scss:

I dunno about you, but this is already looking like a lot of code … and there’s more to add.

We see the following on the screen (corresponds to my image files, which you can check in the repo):

Screenshot by Author. First image of each item is shown.

We need to add the rest of the images to the style sheet, and I have different amounts of images per item. You can imagine how long the style.scss file will get if I just keep copy-pasting the styles and changing the numbers so they correspond to the right images.

Example of how the style sheet would become long and repetitive if we just keep hard-coding rulesets.

It would become difficult, tedious, and error prone to add new items and new images per item. It’d be unmaintainable and frustrating. This is where Sass comes in!

Let’s first tackle the images per item. Each item basically has the same file name, except for the number at the end. We can generate the styles per image under an item using a for loop.

Less repetitive when using for loops to create the rulesets for the different items, but can be shorter.

We’ve reduced the code, but we can do better. If we create a map (a map in SASS has key/value pairs) where the keys are the item folder names and the values are the number of total images for each item, we can reduce the above code down to what resembles a nested for loop, using the @each rule.

Now when new folders/images are added, you just update the items map and the rule-sets will be generated.

Now that we have added all the images to the style sheet in a concise manner, let’s work on implementing the logic for switching between item images on the character (the dress-up functionality).

Add Dress-up Functionality

In the previous section we defined div tags in React with a class name corresponding to the general item (e.g. eyes) and an id corresponding to an specific item (e.g. eyes1) with the intent of switching these items based on the user’s input. The id being changed will change the image shown for an specific item. You can test this by changing the ids of the divs in the React code and reloading the site, or by changing the ids using Chrome DevTools in the Chrome browser.

Video by Author. Video example of how you can use Chrome DevTools to change the ids and test the desired functionality.

We will start by adding “next” buttons per item, so the user can switch each item.

Add styling to the “next” buttons, so they are placed to the right of the dress-up character:

Position “next” buttons. Buttons will have 30px in between (vertically).

When a button for an item is clicked, we want the class name for the corresponding item div to be updated to the next item. For example, when the button titled “next eyes” is clicked, we want the class name for the div with id equal to “eyes” to change from “eyes1” to “eyes2”, or from “eyes2” to “eyes3”, and so on. To achieve this we need to keep track of the current number of each item being displayed and the total number of images available per item.

I decided to use React Hooks in order to use state to keep track of the current image per item and the total number of images per item.

Import "useState" in order to use React Hooks for keeping track of state.

Inside the App() function, define a state variable called dressupState, where we will keep track of the current image per item and the total images per item:

Displayed item names and totals correspond to my images.

Define a function titled next for updating the image for an item:

This function is defined inside App(), outside of return().

Add next() function to “next” buttons:

Next buttons can be written in shorter code by iterating over the keys of the dressupState variable:

Update the divs which were added earlier so that their class values are defined based on the current image per item:

Current’s lowest possible value is 0, but image values start at 1. We adjust by adding 1 to the current value.

The divs can also be written in shorter code by iterating over the keys of the dressupState variable:

Now a user can choose different items using the “next” buttons.

[Bonus] Add Randomize Button

In order for randomly selected items to be displayed, we need to get a random integer from 0 to the total number of images for an item and assign it to the class name of a corresponding item’s div.

I decided to make a function called updateDressUp() which updates the dressUpState state variable, given item and new_current values. I did this in order to avoid repeating the lengthy call to setDressupState.

Move dressup state update to its own function.

I created a function called randomize which, per item, gets a random integer from 0 to the total number of images for the item and sets the new (or same) number as the new current for that item.

Randomize function.

Then I added a button which calls the randomize function when clicked.

Randomize button.

Finally, I added styling to the button. I placed it under the “next” buttons and made the button’s text bold.

Randomize button style.

Final Result

Full App.js code:

Full style.scss style sheet:

Dress-up gameplay:

Video by Author

Deployed dress-up game: https://meramos.github.io/React_Dressup_Game/

Now you have a basic dress-up game or character generator which you can add more features to and customize. You could:

  • add “previous” buttons to go alongside the “next” buttons,
  • add a panel with buttons per image per item so instead of a user having to click through the next buttons they can view and click the exact item they want to use,
  • add functionality to download an image with the user’s selected items,
  • make the site pretty,
  • etc.

Have fun!

If you enjoyed this article please recommend and share.

--

--

--

Puerto Rican computer scientist who enjoys writing helpful articles and contributing to the vast content of the internet.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is Node.Js?

Making a NYSE stock watchlist backend with Node js and Postgres database

VS Code for Web Development

Today’s learning about React.

What I learned from migrating Atlaskit to TypeScript

JavaScript Scope

A Guide to Javascript String and Closures

React + Firebase Hosting: A Beginner’s Guide

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maria Ramos

Maria Ramos

Puerto Rican computer scientist who enjoys writing helpful articles and contributing to the vast content of the internet.

More from Medium

What is a Component in React JS?

Node Version Managers and Why You Need One

An screenshot of the Node.js website showing download links

Context vs. Composition in React

Implement a Schedule in React with Planby component