How to Add GDScript Syntax Highlighting to Your Blog

Recently, I decided to devote more time to writing blog posts, especially tutorials about things I’ve learned in my three-plus years of learning Godot and GDScript. When I went to write my first tutorial post, however, I discovered that there is no support for GDScript syntax highlighting in any of the code formatting plugins for WordPress. On top of that, Github’s Gists, which I’ve used to show syntax-highlighted code in the past, also does not support GDScript.

Syntax highlighting, for those who don’t know, is the colorful text and different font weights and decorations (aka bolded, italicized, and underlined text) that code editors show to indicate different functionalities of code. Using syntax highlighting to show what your code is doing is extremely helpful, if not critically important for making your code readable. Without syntax highlighting, it’s a lot more difficult to parse what a given block of code is doing, to the point where it feels unreadable. For tutorials, it’s especially important to make code as easy to understand as possible, and a critical part of that is including syntax highlighting.

Imagine trying to read a blog article where all the code samples were one giant block of monochromatic text, like this:

It’s a little tricky, isn’t it? Maybe you can read this particular example after a few moments, but what about 20-50 line examples of complex code? And what if you’re scanning back and forth between code samples, trying to parse how the whole thing works? It was clear to me that, if I wanted to write tutorials that were user-friendly, I needed to find a way to add support for GDScript syntax highlighting to my website.

After asking in the Godot Discord, I was pointed towards an implementation of GDScript in highlight.js, a JavaScript-based syntax highlighter. Some additional googling showed me how I could integrate highlight.js onto a website, and further research showed how to make changes to a WordPress website’s head file. Combining this information together, I was able to successfully integrate highlight.js and the GDscript extension for it onto my blog.

First, I went to Appearance -> Theme Editor and edited the header.php file, adding this snippet right below the wp_head() function call, to take care of downloading highlight.js:

<!-- Syntax highlighting for code blocks. -->
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>

Next, I went to the Github repo for hilightjs-gdscript and copied the contents of the gdscript.min.js file, adding it just below where I added the main highlight.js script tag:

<!-- Syntax highlighting for GDScript. -->
<script>hljs.registerLanguage("gdscript",function(){"use strict";var e=e||{};function r(e){return{aliases:["godot","gdscript"],keywords:{keyword:"and in not or self void as assert breakpoint class class_name extends is func setget signal tool yield const enum export onready static var break continue if elif else for pass return match while remote sync master puppet remotesync mastersync puppetsync",built_in:"Color8 ColorN abs acos asin atan atan2 bytes2var cartesian2polar ceil char clamp convert cos cosh db2linear decimals dectime deg2rad dict2inst ease exp floor fmod fposmod funcref get_stack hash inst2dict instance_from_id inverse_lerp is_equal_approx is_inf is_instance_valid is_nan is_zero_approx len lerp lerp_angle linear2db load log max min move_toward nearest_po2 ord parse_json polar2cartesian posmod pow preload print_stack push_error push_warning rad2deg rand_range rand_seed randf randi randomize range_lerp round seed sign sin sinh smoothstep sqrt step_decimals stepify str str2var tan tanh to_json type_exists typeof validate_json var2bytes var2str weakref wrapf wrapi bool int float String NodePath Vector2 Rect2 Transform2D Vector3 Rect3 Plane Quat Basis Transform Color RID Object NodePath Dictionary Array PoolByteArray PoolIntArray PoolRealArray PoolStringArray PoolVector2Array PoolVector3Array PoolColorArray",literal:"true false null"},contains:[e.NUMBER_MODE,e.HASH_COMMENT_MODE,{className:"comment",begin:/"""/,end:/"""/},e.QUOTE_STRING_MODE,{variants:[{className:"function",beginKeywords:"func"},{className:"class",beginKeywords:"class"}],end:/:/,contains:[e.UNDERSCORE_TITLE_MODE]}]}}return e.exports=function(e){e.registerLanguage("gdscript",r)},e.exports.definer=r,e.exports.definer||e.exports}());</script>

Imagine trying to read the above without syntax highlighting!

Finally, I added a call to initiate highlight.js, right below the highlightjs-gdscript code:

<script>hljs.highlightAll();</script>

And with that (omitting some trial and error on my part to figure out the above), I successfully got highlight.js to run on my WordPress blog, with syntax highlighting for GDscript!

I wasn’t happy with the out-of-the-box highlighting, though, so I decided to quickly throw together some custom styles, targeting the classes highlight.js injects. First, I went to Appearance -> Edit CSS in the WordPress menu settings and injected this CSS styling:

:root {
    --code-background: #000004;
    --default-font-color: #fbfef9;
    --keyword-color: #7e1946;
    --title-color: #a63446;
    --function-color: #0c6291;
    --string-color: #6ea735;
    --html-color: #a76e35;
}

code {
	border: none;
	padding: 0;
	font-size: 0.9em;
}

pre, code, code.hljs {
    background: var(--code-background);
    color: var(--default-font-color);
}

code.hljs .hljs-function,
code.hljs .hljs-function .hljs-keyword {
    color: var(--function-color);
}

code.hljs .hljs-keyword {
    color: var(--keyword-color);
}

code.hljs .hljs-title {
    color: var(--title-color);
}

code.hljs .hljs-string {
    color: var(--string-color);
}

code.hljs .hljs-name,
code.hljs .hljs-tag,
code.hljs .hljs-attr {
    color: var(--html-color);
}

I also made changes to other parts of the highlight.js syntax highlighting that weren’t for GDScript to make them work with my new color scheme.

I also noticed that highlight.js wasn’t consistently auto-detecting when I was using GDScript, so I converted my WordPress code block to an HTML block and created the code tags manually:

<pre class="wp-block-code"><code class="language-gdscript"></code></pre>

Finally, highlightjs-gdscript didn’t include support for print, so I quickly added that to my import of the dist file:

{ keyword:"and in not or self void as assert breakpoint class class_name extends is func setget signal tool yield const enum export onready static var break continue if elif else for pass return match while remote sync master puppet remotesync mastersync puppetsync print" }

The final result looks like this:

At least, that’s what it looked like at the time I wrote this blog post. Since I was just looking to throw something together quickly, I didn’t put too much thought into my color scheme, instead utilizing a randomly-generated color palette (https://coolors.co/a63446-fbfef9-0c6291-000004-7e1946) and some hue-shifting to get related colors that weren’t part of the generated palette. Below is what the syntax highlight looks like on today’s iteration of the color scheme:

func ready():
  var variable = some_function()
  print("Hopefully this syntax highlighting works!")

Anyway, that’s a quick overview on how I implemented GDScript syntax highlighting on a WordPress blog. I imagine much of this can be adapted to implement GDScript syntax highlighting on any site. Now, on to writing blog posts!

React Hangman Koji Template Released

If you follow me on Instagram, you probably know that I have been working on a game template for Koji for the past few months. It started out as a portfolio project for me when I was looking for a job, and even after I got the job I decided I wanted to finish it and release it as a template for other Koji users to build their own apps on top of.

Well, today is the day of the first public release! Go play it here: https://withkoji.com/~Jantho1990/react-hangman

It’s intended to be a template, but the base app is fully playable in its own right!

I invite you to play the game and leave a comment on how you felt about it. Any feedback is helpful!

Bumbling Dwarves

I discovered Koji recently. Basically, it’s a service where coders create templates of projects, including games, for other people to download and customize in whatever ways the programmer allows them to do. Not only that, but the end user can also access the code for the template and make changes to that as they desire.

Figuring I’d give the service a try, I signed up for an account and spent tonight crafting my first game on the platform, a Match-3 clone based on their starter template called Bumbling Dwarves. You can click the link to play, or play it in the embed below!

Working with Koji was pleasant. Honestly, the majority of the time I spent on this project was restyling the open-source artwork I used for this project, as the original images clashed with each other. I wound up coloring the dwarf sprites to be visually distinct, and I softened the lights on the background image.

Using the template was easy, and it made everything simple to customize, just based on the template alone, and for the few code customizations I made (such as changing the color of the selection box) I had full access to the source code (the template was written in React).

The primary way you interact with the code is through Koji’s online editor, which is based on the Monaco editor (the same one that powers VS Code). They give you two ways to interact with the settings files: a visual editor which functions like a form, and the underlying JSON file that you can change in the editor. When I was finished making my customizations (including custom sounds and music), I filled out their short publication form, hit the publish button, and after a few minutes the project was published on https://withkoji.com/, where their projects are hosted.

I can definitely see how this perpetuates Koji’s mission of making app development and MVP prototyping fast, easy, and accessible even to non-coders. If not for those pesky images, I could easily have deployed Bumbling Dwarves in an hour or two.

This was a fun experience overall, and I’m thinking about messing around with Koji more in the near future. At the very least, I’ll be keeping tabs on this cool, interesting service.

If you want to check out other Koji projects from other users, visit https://withkoji.com/

Post-Mortem Ludum Dare 43

Outside my home office window, fluffy flakes of snow drifted down from the night sky, coating the ground in white, hiding the dreary brownish grass. It was a picturesque scene, and I allowed myself a brief moment to enjoy it; but then my focus turned back to the task before me: crafting the finishing touches of a sample game UI. A last practice project, in preparation for the challenging journey I was about to undertake.

In less than an hour, Ludum Dare 43 — a video game competition wherein participants design, develop, and deploy a video game in 72 hours — would begin, and I wanted to be sure my mind was primed and ready to roll the moment the competition began.

Before you continue further, dear reader, let me forewarn you: this is no mere post, simply detailing the development of a video game. This is a tale of hopes and dreams, of fear and despair; a tale of lessons learned, best laid plans, and desperate decisions; perhaps most of all, it is a tale of one man’s journey to stare dread fate in the eye and dare to succeed.

This, then, is the tale of my experience creating Sanity Wars for Ludum Dare 43, in all its horror and glory. Sit down, buckle up, and hold on.

The Beginning

I’d reserved today — November 30th, a Friday — and the following Monday and Tuesday off on PTO, in preparation for this weekend competition. I’d spent nearly a year teaching myself how to create video games, and now was when I felt my skills were sufficiently advanced enough to tackle a real challenge: Ludum Dare, a legendary video game competition where participants are given 72 hours to create a brand-new video game.

Though unconventional, I planned to enter the contest with a custom JavaScript-based engine that I coded myself, from its humble beginnings as a tutorial engine to its current state, with my unique experiments and needs added to it. It was general enough that I felt comfortable putting it to the test in the fires of competition.

This was an important moment for me. One of my dreams has been to create and release a professional video game, and to me this contest felt like the perfect opportunity to test not only my skill, but also my resolve. How would it feel to channel my creative and intellectual effort into making a video game? Would I enjoy the process enough to commit to wanting to make a full-fledged game later on down the road? Could I make a game that people would enjoy playing? Over the next three days, I reckoned, I’d find out the answers to these questions.

Let the Games Begin! (Friday Night)

At 8 p.m. CDT, the theme for Ludum Dare 43, voted on by its participants, was revealed: “Sacrifices Must Be Made”. I was pleased; this was one of the options I’d been voting for. As a creator, I’ve always been partial to the thematic and narrative drama sacrifice offers, and I knew I’d be able to come up with something that would fit this theme.

Pacing back and forth in my home office to get my creative juices flowing, I hashed through various different possibilities. Eventually, I settled on a general idea for the signature game mechanic: a side-scrolling platformer where the player used a resource called “sanity” to cast spells — but their sanity was also their health bar, and casting too many spells would deplete their sanity below zero, causing the player to die.

Additionally, players would not be able to access these spells at the start of the game; they’d instead start with something called a “sanity buff” which increased sanity recharge rate. If the player chose to sacrifice these buffs, they’d gain access to spells, but also decrease the rate at which their sanity recharged.

The narrative theme I created to support this mechanic was that the player would be fighting a malevolent being named the Dread Overlord, who held the entire world under the sway of terror, and that the player’s narrative goal would be to weaken the Dread Overlord’s iron grip, bringing salvation to the world. In this, the game also served as a loose allegory to the struggle with bipolar disorder, a struggle I am intimately familiar with, and that further endeared me to the idea. It was, I felt, a perfect fit with the sacrificial nature of the theme, as well as the sanity-casting and buff-sacrificing mechanics.

Little did I know of the irony this narrative theme would present later on in the competition.

With my initial planning made, I sat at my desk and immediately began prototyping my sanity-casting mechanic. It so happened that I already had a spell-casting mechanic built from a previous experiment. Using this as a base, I managed to hammer out a working prototype of the mechanic by early morning. The player’s hit points, or HP, would be directly tied to their mana — or, as I was calling it, “sanity”. Spells could not be accessed until their hotkey was held down for a long-enough period of time — aka a “sacrificed” sanity buff. Reducing sanity to below 0 would trigger the player death state, though I had yet to code what that actually looked like.

I also came up with a tentative title for the game: “Sanity Wars”. It wasn’t a perfect title, but I’d spent half an hour brainstorming possible titles, and this was the one that felt the least cheesy. I figured I’d revisit it later and come up with something better, near the end of the competition.

Feeling satisfied with the current state of things, I decided to call it a night and get some sleep. My confidence at this point felt solid; I believed that I had enough time to take this vision I’d come up with and hammer it out. Soon, I was fast asleep.

Time Management Issues (Saturday)

Around 8-9 a.m. CST, I woke up to a breakfast prepared by my wonderful, amazing wife, and I enjoyed the family meal before returning to the office to begin the day’s work on my game. The first thing I did was to finish implementing player death, which didn’t take much time. I just tied the player HP stat to mirror the sanity level.

Now that I felt I had the “core” of the game implemented, I thought about what to tackle next. I’d noticed the tileset I’d been working with included sloped tiles, but my engine didn’t have support for moving on a sloped tile. So…why not knock that out real quick?

Three hours later, I had a very buggy implementation of slopes; try as I might, I simply could not get the physics of walking on the slope to work correctly. At that point, I finally asked myself the question that I should have asked myself before I started working on slopes: Is this a feature I really need in my game?

The answer was glaringly obvious: No, it did not. I had been developing just fine with block tiles and jumping around, and while I loved the idea of including slopes, they were far from essential for my game to work. Thus…I nixed the idea and moved on. Three hours, down the drain, over a needless feature…

Lesson Learned: Question whether the feature you’re planning to add is necessary before writing code for it.

I decided my next goal should be to implement an enemy. Hitherto, all I had was a player and the sanity mechanic for casting spells. There needed to be at least one enemy, ideally more, for the player to contend with.

I decided I wanted to create a flying enemy, to avoid having to deal with determining where a ground character could move. After perusing OpenGameArt.com for a considerable period of time, I found a floating eyeball animation that looked delightfully menacing. With that as my art base, I created a floating eyeball entity, which would fly at the player, then back away to a random distance once they got too close, then either wander around for a bit or immediately descend upon the player again. When they were close enough to the player, they would trigger a sanity drain, thus “attacking” the player. It took another few hours, but it was complete and I had it integrated into Tiled (the tilemap editor I was using), so I could place floating eyeballs anywhere I wanted.

By then, the hour was getting late. I took a short break, to ponder my next moves. That was when it finally dawned on me: I had a mechanic, I had a player, I had an enemy…but I had no core game loop. In other words, I had no goal for the player to attain, no objectives to attain along the way. All I had was a map with a sanity caster and a few floating eyeballs. That wasn’t a game, that was a setup.

What was the player’s goal? In order for my game to truly be a game, I needed to answer that question, fast, and then implement the bare minimum necessary to make that goal playable.

Lesson Learned: Hash out the core loop for the game right away. Maybe it will change later, but at least have an initial iteration.

After some brainstorming — I can’t recall exactly how long — I settled on the idea that the player needed to survive and find a Final Exit, but this wouldn’t be considered a true victory unless the player first found some Objective; both the Final Exit and the Objective would be randomly spawned in one of a series of maps. Each map would be connected linearly by portals. I felt these things should all be doable within a day or less, and now that it was past 1 a.m. of the next morning I decided to go to bed now. Hopefully, this would give me the energy needed to bang things out quickly.

Making the World (Sunday)

The next morning, I woke up, scarfed down a quick breakfast, then headed back into my home office to start implementing the Map Portals mechanic. Up until now, I had been working with isolated test maps. In theory, I should be able to write code which would create two portals on a map, each linking to a different map, as determined by the load order in my map configuration file.

I spontaneously decided that I wanted the player to be spawned randomly as well, and that furthermore I wanted the player to spawn only in a map corner. Thinking that this shouldn’t be too hard, I got to work designing and implementing the code that would let me do this.

It took more work than I thought it would. I not only needed to restrict where on the start map a player could spawn, I also needed to check and make sure the spawn location was actually habitable by the player (in other words, not inside a solid tile, like a wall) and directly above a ground area (so the player wouldn’t spawn at the top of a tall map in mid-air). After several hours, I had the mechanic working, and proceeded to work on the Map Portals.

A lot of the spawning logic I used for the player also applied to spawning Map Portals, so I made use of copy-pasta and removed the map corner restriction. I then needed to add logic to prevent map portals from spawning on top of each other (or the player), as well as logic to prevent portals from spawning too close to each other.

Another several hours later, I had the portal spawns complete. Now, for the challenging part: enabling the player to press a key in front of one of these portals, and be teleported to the correct corresponding portal on the linked map.

It turned out to be even more complicated than I expected. First, I had to set up a system by which two portal objects could be “linked” together so that they’d always send the player to the correct location. Then I had to load the next map’s data into the game while swapping out the old map data (but not deleting it, because I’d need to restore it when the player returned to that map). The player also needed to be teleported to the receiving portal’s coordinates, which involved resetting the camera to focus immediately on the receiving portal’s location and preventing the player from accidentally teleporting back to their original location by holding the action key a fraction of a second too long. There also needed to be logic to determine where the Final Exit would be spawned, and only render the object when the player was on the chosen map. Finally, any additional entities (enemies, the Objective) on one map needed to be removed from the game loop, then put back in when the player returned to that map.

In short, I needed to make maps containing bad guys, portals, tomes, and the exit.

I spent the entire rest of the day just implementing all this logic. Along the way, I decided, instead of a single Objective, to create multiple Objective pickups (which I ultimately decided to call Tomes, giving them a bookish sprite), spawning one on each map, and that the player had to collect all of them to get the “best” ending; anything less would result in achieving a subpar ending. I also wound up having to write a custom events handler to run dispatches at the end of the current rendering cycle as part of making these portals work, as well as a WorldMap handler specifically to handle the metadata outside of each individual map.

Working feverishly, hour after hour, I finally had everything functioning as intended, except for enemy persistence. By now, it was nearly two in the morning. I had intended on composing an original song for this game, but some part of me warned myself that I might not have time for that on the final day, so I listened to a few of my older compositions and picked the best-fitting one as my backup soundtrack.

Lesson Learned: Things will take longer than expected, so account for that when planning.

Utterly exhausted, I collapsed into bed and tried to fall asleep. I tossed and turned, and I growled mentally at my body for being so stubborn…but sleep continued to evade me. At that point, thoughts flooded into my mind about how every minute I spent awake in bed would lead to one less minute of sleep I’d get, because I absolutely could not afford to sleep in late this time, like I did the other days.

After hours of this dreadful torture, I did finally fall asleep, but not for very long.

Dread Realizations (Monday)

At 8:00 a.m., the alarm blared and yanked me out of my fitful slumber. Compared to the other days, my mind was besot with grog and lack of clarity from the get-go. I plodded to the fridge, grabbed an energy drink, and started downing it. I had no time to think, no time to reflect; I had to finish enemy persistence, and whatever other little things I’d forgotten, to at least get the game to a playable state.

I thrust myself into the chair before my laptop and got to work. In another couple of hours, I got the enemies to correctly persist across maps. I also implemented a maximum enemy amount per map, and a rate which enemies would spawn/respawn into the map. I also threw in some simple ending screens to test the end-game conditions.

It was past noon by the time I got all this working. Meanwhile, my wife was playtesting builds of the game on another machine, and I would need to run back out there multiple times and pull down the latest builds for her to test with.

At this point, with the core loop finally in place, I decided to start looking around for final art assets. The ones I’d been testing with weren’t bad, but they didn’t quite fit together, and it bugged me enough that I chose to divert time into searching for new assets. Hours passed, and before I knew it the time was 4:00 p.m., and all I had to show for it was a single tileset and new sprites for the character.

The deadline was at 8:00 p.m. In short, I now had four hours to create the actual levels, create music, create sound effects, add story text and cinematics, upload the game to a server, test everything…that’s when it finally hit me: I’m not going to be able to release my full envisioning of the game.

It was at this point that my bipolar symptoms, hitherto under control, started to flare up strongly. Dark thoughts filled my mind about how badly I’d executed this game, how unlikely it was that I would even be able to get it finished. Every tiny little mistake I’d made, from the botched slopes to the overly-long search for a new tileset, flooded into my mind.

“You’re not good enough for this,” my brain whispered to me. “You did your best, but it wasn’t good enough and you’re going to fail.”

I kept trying to push forward with making levels. Nearly an hour later, I only had a single map that looked somewhat decent, and my mental anguish only intensified with each passing minute. There were now entire minutes where I’d find myself paralyzed with derision, my mind crushed under the anguishing weight of despair, my body unwilling to even move a single muscle. It had been a long, long time since I’d felt such intense levels of depression, and this scared me most of all. If this is what it’s going to be like every time, how can I justify making games in the future?

Sanity Wars, indeed. The imagined narrative of my game — of which I had yet to even write a single line of text — proved utterly ironic as the villain of my game threatened to consume the game’s creator.

Somehow, despite mostly working in fits and spurts, I kept forcing myself onward, even as my depression screamed at me about the futility of such gestures. My wife helped out by creating a map of her own, and I threw together a few additional barebones maps with a few randomly-drawn platforms. I found a few open-source sound effects to combine with my sfxr-generated effects I’d already put into the game, and I also took the backup music I’d selected the night before and added it as the game’s soundtrack.

Somehow, with less than two hours until the deadline, I wound up with a playable game. It was nowhere near the game I’d envisioned it to be when I started the competition; compared to that, it was abhorrent, abominable, awful garbage. Yet…it was still a game, and it was playable.

The Dread Overlord was still doing his best to crush my mentality and inconvenience my efforts, but, nevertheless, I slogged on. At this point, I had steeled my resolve. It was going to be a crap game, it wasn’t going to capture the theme nearly as well as I’d planned, and it was surely not going to do well…but I was going to finish and release it, flaws be damned!

The Final Push (Monday Night)

Now that I had something to release, it was time to ensure that the game did get released. Although it felt a little early–I still had an hour and a half of time–I decided to go ahead and set up the release platform for my game, so I wouldn’t be scrambling to do it at the literal final hour. As this was a web-based game, my plan was to host this as an AWS S3 website, where I wouldn’t have to deal with setting up and hosting a server, or learning some other company’s setup for their own hosting service. My decision to tackle this now would prove fortunate.

I mentioned previously that I’d built my game-engine based on a tutorial book. Said tutorial book gave instructions on how to set up a dev server called Budo for use with the testing environment…but, it turned out, had not provided any instruction on how to actually deploy the finished app to production. Scrambling, I rapid-researched how Budo ran under the hood, discovered it was using Browserify, and figured out how to set up Browserify to deploy a production build of my game script. After a few other snafus, I managed to correctly set up a deployment script.

Now it was time to create the S3 bucket-site and copy my production assets into it. In my depression-paralyzed state, I screwed up my first deployment attempt and spent almost half an hour trying to fix my AWS permissions before finally opting to blast the first site and make a new one. The second time through, I set the configuration correctly, and the deployment worked as intended. With less than an hour to go before the deadline, I at least knew I could reliably deploy the game.

I used every minute of that last hour to add as much polish as I dared get away with. By now, the adrenaline of deadline crunch was overcoming the dread weight of my depression, so I was singularly focused on trying to make my game at least not absolutely terrible. I converted my test ending screens into actual ending screens, so that I could at least get some of the story’s context into the game. My wife helped by writing the actual dialogue for the ending scenes, while I crafted the introductory scene establishing the game’s tone. We got the final words in, and deployed, at literally the last possible second, at 8:00 p.m.

At the end of the deadline, Ludum Dare allowed for a single hour to get the game deployed, and to fix any last-minute bugs that come up during this process. I honestly don’t recall much of what I did at this time, other than fixing a few things. At the end of it, I belatedly marked the game as “Unfinished” as I crafted the submission post. It only seemed fair, with the game in a barely-publishable state, to mark it as such. When I made my submission post, however, another fellow Ludum Dare-r messaged me, advising me to mark the game as “Jam” instead of “Unfinished”, pointing out that hardly anyone was going to play a marked-unfinished game, and I thus wouldn’t get any feedback on where I could improve. Deciding that I could at least treat this as an improvement opportunity, I took the person’s advice and changed my submission type to “Jam”.

Shortly after I did this, 9:00 p.m. hit. The competition was truly over, and now no changes were allowed. I collapsed onto the living room couch, utterly exhausted and in a foul state of mind. My wife tried to cheer me up, to focus on the fact that I had actually finished and released the game. I wasn’t quite ready to rejoice over that fact, especially since I found myself dreading the horrible reviews which would surely come.

But she was right: I had finished the game. It was a poor excuse of a game, in my mind, but I had actually done it. I’d built a game in three days, and on my first-ever attempt at such a feat. It wasn’t at the standard of quality that I hold myself to, but it was something.

Ultimately, I opted to push all thoughts of self-review and criticism out of my mind until I had gotten a good night’s rest. Fumbling my way through my regular nightly routines, I fell asleep mere minutes after tumbling onto the bed. It was a deep, deep slumber.

The Judgment

I didn’t get out of bed until nearly 10:00 a.m. the next morning. Immediately I noticed an improvement in my mood; sleep had seemed to help tremendously. At the least, I could finally acknowledge to myself that, yes, I had finished a game, and take some pride in that fact.

Lesson Learned: Never underestimate the value of good sleep. Working rested makes a huge difference not only in how you feel, but in the quality of work you output.

Now that the development part of the competition was over, each participant in the jam was expected to play each other’s games, rate them, and provide feedback. I hopped onto my desktop and started checking out the various games. I played a lot of clever implementations of the sacrifice theme: as a game mechanic, as part of a narrative, as the goal for the game…the creativity from the other developers was on full display.

All the while, I kept checking back on my own game. To my surprise, people were not only playing the game…they didn’t completely hate it. Sure, there were critiques on numerous aspects of the game, many of which I was expecting; but there were also plenty of positive comments about some things which they thought I’d done well: the choice of game genre, the incorporation of spellcasting, the visuals and audio… I hadn’t been expecting anything positive, so these comments pleasantly surprised me.

Over the course of the month of December, I continued to play other games (though not as many as I’d have liked, due to work obligations and the holiday season) and give my own ratings and feedback. Other people continued to play my own game and leave their feedback.

At last, at the beginning of January, the ratings period was officially over, and the scores were released for every game. I logged onto the site, and found my results:

The final results from my debut game entry, Sanity Wars.

With my own numbers known, I went to check on the overall stats for the jam, from which I’d learn how high my score truly was:

The overall statistics from Ludum Dare 43.

There were 2,514 submissions. Of these, 1,494 had received enough ratings (20 or more) to be awarded an official ranking.

Thus, my final placement: 842nd out of 1,494. Right in the middle of the pack.

To me, the final score was both surprising and expected. Expected, because this was within the middling range where I felt I’d wind up with my first-ever game entry. Surprised, because I never expected this flawed, imperfect game to score so highly. It still amazes me even now, as I type this retrospective.

It just goes to show: Never give up, even when all hope seems lost. This adage is a mantra that I try to live by, contending with my bipolar disorder, and time and time again I find it to be a true maxim. With my emotions screaming failure, I persevered and found triumph.

I Am Now a Video Game Developer

It’s official, now. Having designed, built, and released a video game, one which people were able to play, I am now a video game developer. It feels good to say that, after all the learning and preparation I put in to get to this point.

Overall, this competition was an incredible experience for me, in many ways. I set out to make my first-ever game, and I not only succeeded, I did better than I expected of my entry. Though I still wish I had been able to release a more polished game, the experience I’ve gained was invaluable, and will prove critical to my future endeavors to publish a full-fledged video game.

Among the things I learned: coding a game engine from scratch is hard. I mean, I knew that, and I knew that the main reason I did build an engine was to learn how things worked from a general perspective, but it gave me a whole new appreciation for the work game engine developers put in to make usable, reliable engines for others to use. Although I like tinkering with systems and how things work under the hood, Sanity Wars drove home a well-worn adage in the games industry: make games, not engines.

I also think I tried too hard to come up with a complex narrative for a game that, ultimately, did not need much narrative involvement. Presenting an allegory of the bipolar struggle may be neat for short stories, but it didn’t translate well into a game. I’m a narrative-oriented person, so I like creating complex narratives; however, by focusing too hard on cleverly implementing sacrifice in Sanity Wars‘ narrative, I instead sacrificed the fun of the game mechanics. In the end, I felt neither the narrative nor the spell sacrifice was well-implemented, and I could have done both more simply by highlighting the sacrificial nature of tying spellcasting to your health.

My goal with taking part in Ludum Dare was to gain experience, and in that regard I achieved success. Most of all, I learned that I can, indeed, create video games, and that this is something I want to keep doing, depression be damned

To put it in a melodramatic way…I faced the Dread Overlord, and conquered him

What’s Next?

I am currently working on rebuilding Sanity Wars in Godot, an open-source game engine, and comparing the experience to coding everything by hand. I suspect it might ease many of the pain points I had developing my game and engine.

Why did I choose Godot, over something more familiar to my background, such as PhaserJS? Well, I read plenty of good things about its ease of use, and the node-based architecture is very similar to the structure I used in my own engine. Plus, I thought it’d be nice to have a GUI to work with, instead of coding everything by hand. I plan on releasing the Godot version of Sanity Wars once I’ve finished the port.

The next Ludum Dare is at the end of April. I’ve already made sure to take time off for the dates of that contest. I look forward to taking on whatever challenges it throws my way, with the goal of releasing a more polished game.

As for my dream of making a professional video game? That dream is alive and well, and as I continue to learn and grow my skills, my confidence that this dream can be realized continues to grow. And as long as I keep moving forward, and don’t give up, I have no doubt that one day this will no longer be a dream.

It will be reality.

You can play the Ludum Dare version of Sanity Wars here.

Sample Project: Star-Rating (Vue)

This is part two of a multi-part series about React and Vue.
Part 1: React
Part 2: Vue

As I have been learning React lately, I’ve also been learning Vue. I currently use Vue at work, but I wanted to make a sample project for myself. I’ve been interested in doing a comparison between React and Vue, so I’ve chosen to build a Vue version of the Star-Rating app I built in React. The app is small and simple: you have a rating represented as a line of stars, and you can change how the star rating is calculated via an inputs component.

For the final result, click this link.

This tutorial presumes a basic knowledge of HTML, CSS, and JS, along with some basic knowledge of how to develop using a command line interface (or CLI) and how to use Node Package Manager (or NPM). If you’re unfamiliar with any of these things, feel free to make an online search for whatever you don’t know.

Vue makes some use of ES6 syntax, and I try to write my code using ES6 as well. I’ll try to link to definitions of ES6 syntax when I initially use them, but I won’t take especial time to explain them in-depth. If you want a quick overview of ES6, you can read this.

Table of Contents

Setting Up
Looking Around
Creating Our First Component
Rendering Stars with FontAwesome
Calculating How Many Stars to Render
Rendering the Stars
Vue Slots
Finishing the First Component
Introducing a Second Component
Rendering the Input
Adding the Other Inputs
Better Validation
Final Touches
Conclusion

Setting Up #

For this tutorial, I chose to use vue-cli, a command-line tool that will set up a boilerplate Vue single-page application, similar to create-react-app. If you don’t have it already, you can install it via npm install -g [email protected].

I’ve specified a specific version number because, as of this post, vue-cli V3 is in beta and will be released soon. It works differently from V2, so to follow this tutorial you’ll need a V2 version of the tool.

To set up a project, navigate in the terminal to the directory you want to make the project in (for me, this is ~/jdev/projects), and then enter this command:

vue init webpack star-rating-vue

Right away, you’ll be presented with a text interface that asks you a number of questions regarding how you want to set up your project. But, before we get to that, let’s look at the command we just entered. The first part is vue, calling the tool; the second part is init, which tells the tool to start up the project; and the fourth part, star-rating-vue, is the directory our app is going to be saved in. So what is the third part, webpack, for? The way vue-cli V2 works is by using pre-built templates, and which template you choose determines what kinds of goodies you start out with. In this case, we’re using the “webpack” template, which will set up a full Webpack-based project, as well as a few other things:

vue-loader
Allows us to write single-file components (we’ll get to that momentarily).
hot-reload
Allows us to see changes to our app on save.
linting
Helps enforce proper coding conventions by marking up your code editor.
testing
Sets up a unit testing framework. (We won’t be using tests in this tutorial.)
css extraction
Pulls our CSS out of single-file components (we’ll get to that momentarily, too).

If you look on the official page for vue-cli, you’ll find some other “official” templates you could use, instead. There are also third-party templates; just search online for “vue third-party templates” and you’ll be bound to find some.

Now that we’ve taken a brief overview of what templates are, let’s get back to the actual setup. The command line tool will present you with a set of options, one at a time. For most of the options, you’ll need to type in either y or n and hit enter to make your choice; some are multiple choice, and a few involve typing up strings.

I’ll go over each option briefly:

  • Project name: “name-of-your-project” (requires URL-friendly characters, so no spaces; also, no capital letters allowed)
  • Project description: “Whatever description you feel like including.”
  • Author: “Your Name <[email protected]>” (if you have a global Git user, this should be autofilled).</[email protected]>
  • Vue build: Here, you’ll have two options: Runtime + Compiler and Runtime-only.
    • Runtime + Compiler allows more flexibility in how you build your projects, such as passing in templates as a string (from an AJAX call, for example), but it makes the final build larger (by as much as 30%).
    • Runtime-only is a lighter build, and performs slightly faster, but imposes some restrictions on how you can set up your project.

    We shouldn’t need any functionality from the compiler for this project, so let’s select Runtime-only.

  • Install vue-router? vue-router is useful for setting up something resembling url navigation within an SPA. We won’t be doing that here, so you can choose n.
  • Use ESLint to lint your code? If you care about following style guides, choose y, and then pick the linter you want to use in the subsequent section. Otherwise, choose n.
  • Set up unit tests: As mentioned earlier, we won’t be setting up unit tests here, so choose n.
  • Setup e2e tests with Nightwatch? Nightwatch is a testing tool that allows you to render the app in full, then set up “scenarios” of user actions to test how your app acts under those circumstances. We will not be doing that here, so you can choose n.
  • Should we run `npm install` for you after the project has been created? Since we would need to do this anyway, go ahead and choose Yes, use NPM. If you prefer Yarn, you can choose that instead.

After that last choice, vue-cli will get to work setting up your app with the choices you’ve made. It may take a while, depending on your internet speed, but in a minute or two your boilerplate app should be generated and ready for you to work with. When it’s finished, start the development server by cd-ing into the project directory and typing npm run dev. Open a browser and navigate to localhost:8080; if you see the Vue logo and some links, the dev server is successfully running!

If you don’t want to use vue-cli, you can import Vue directly, via a CDN, locally-hosted script, or NPM install. Check out the official docs for more information. For this tutorial, however, I’ll be assuming you’re using vue-cli.

Looking Around #

Now that we’ve (finally) got the barebones project set up, open the project in your preferred code editor.

If you use VS Code, you can spawn a new editor window from the project directory by cd-ing into it, then typing code . (you may need to explicitly enable this if you use a Mac). Other code editors likely support this functionality as well, though the commands you use may be different.

You should see a number of directories and files already set up. Let’s look in the src directory and open up the file called main.js. It should look something like this:

This file sets up the root Vue instance. All the other components in our application will be kept under this root instance. We’re importing Vue itself, as well as a file called App (which we will be examining shortly). There’s a quick line disabling the production tip. Finally, we create a new Vue instance, and pass in a config object with two settings:

  • el: '#app' This tells Vue what element from the HTML document to bind the instance to. The original element will be replaced with our rendered application. (You can see this element by looking in the `index.html` file in the project root directory.)
  • render: h => h(App) This tells the instance’s render function what should be rendered, via passing in a callback function that handles the actual rendering. In this case, we’re rendering the App file imported at the top of the page.

Let’s dig into that second option a little bit. The code is using an ES6 arrow function, with a single argument: h. What’s h? It’s an alias for the createElement function, the letter itself short for “hyperscript” (you can check this Github issue comment for a deeper explanation of both the render prop and the meaning of h). h is then called, and App is passed in and rendered.

So what is App doing? Let’s find out:

Note the .vue extension. This is what Vue calls a Single File Component. A single file component allows you to write your HTML, JavaScript, and CSS for that component in the same file. For applications comprised of multiple, modular parts, this can be very useful for keeping markup, logic, and styles associated with a single component located in one place. We will be creating our own single file components (henceforth just “components”) soon enough, but first let’s dig into the default App component, section by section.

First, the HTML:

The entire section is wrapped in a template tag. This gives Vue access to the markup contained within; the tag itself will not be rendered. Next, you have a single div with an id of app. This is not the same app element that the root Vue instance replaced; it merely shares the same id. Finally, we have an image tag — the Vue logo — and a strange-looking, self-closing tag named HelloWorld. This is another component, imported into App and being rendered below the logo.

All elements in your component must be wrapped by a single container element; here, the #app div.

Next, in the javascript section:

This contains the JavaScript code for the component. First, you’ll see the HelloWorld component being imported from the components directory. Next, the code exports an object as default, containing two properties:

  • name The name assigned to this component. While not strictly required (except in a few cases), it’s good practice to always give your components names.
  • components This tells the component instance what custom components should be expected. This is how we can write <HelloWorld/> in our template and have Vue replace it with the template from the HelloWorld component.

Finally, there’s the styles section:

This is just regular ol’ CSS, styling the #app element. During development, these styles will be added to the <head>, but because our Webpack template includes CSS extraction, the styles in this section will get pulled out and added to a single CSS file during the build stage.

That does it for App. Now let’s look at the other component included in the boilerplate — the HelloWorld component.

As you may have noticed, the attributes for the a tags in your local file are split onto separate lines. This is considered by Vue’s style guide to be best practice. I’ve chosen to condense the tags back onto one line for my gist for the sake of brevity, but in general I agree with this philosophy.

It’s another single file component. The HTML template contains a couple unordered lists of links and some h2 tags titling them, as well as an h1 with {{ msg }}. If you’re looking at the app in the browser, however, the h1 says “Welcome to Your Vue.js App”. What’s going on?

Let’s look in the script section to find out:

There isn’t much here. We have the component’s name, “HelloWorld”. There are no components being passed in; however, we do have a method called data, which returns an object. This object contains one property: msg, whose value is set to “Welcome to Your Vue.js App”. Hey, that’s what the h1 says on the rendered page! That’s where it comes from. Anything you set in a Vue component’s data method becomes available in your template as a variable. You can output the values of those variables using a pair of curly braces.

Why is data a method returning an object, instead of just being a property set as an object? If you have multiple instances of the same component on a page, each component’s properties are shared with each other by reference. Thus, if data were an object, updating the data on one component would update that piece of data for every instance of that component. To avoid this, we just make data a method that returns a fresh object each time it is called.

The docs provide additional explanation, as well as an example.

Lastly, let’s take a look at the style section for this component:

Again, it’s just CSS, but this time there’s a scoped attribute in the style tag. This means the CSS in this component will only be applied to styles within that component. How does it do this? If you go to the web page and do a dev inspection on one of the links, you’ll notice there’s a data attribute attached with a long, random string (prefixed with data-v-) as its value. Vue sets the CSS rules in HelloWorld to target both the rule specified in the code and the value of this data attribute. Thus, the styles in this component will not affect anything outside of its scope.

You are still able to affect the element styles in this component from the outside, but be aware that, since the data attribute specification adds specificity, you may need to be more explicit with your rule declarations than usual to override the component’s styles.

Whew! For a boilerplate example, that was a lot of stuff to look over. Hopefully, this overview gave you a basic idea of how Vue works; the rest of what we need to know, we’ll pick up as we go along. Let’s start making our Star-Rating app by creating our first component!

Creating Our First Component #

In the “components” directory, create a new file and name it StarRating.vue. Here’s the structure we’ll need to start with:

In the template section, we’ve just added a single div with a class of “star-rating”, which will serve as the container element Vue requires. That’s all we’ll add, for the moment; we’ll get to adding stars shortly.

In the script section, we’re exporting a default object with two properties: name, and props. Props are pieces of data that a component expects to be passed down from a parent component. We’ll be setting up App to do that, but for now we’ll just set up defaults to work with. We’ll also add a type property to each prop, which allows Vue to detect when a prop gets passed down that doesn’t match the type specified, and warn you in the developer console.

The style section is currently empty. Eventually, we’ll put in the styles specific to the StarRating component, but first let’s have something to actually render.

Rendering Stars With FontAwesome #

If you read the React version of this sample project, you’ll remember that we chose an icon set called FontAwesome, imported some star icons into our app via a series of NPM libraries, and wrote some logic to control how to render those icons. We’re going to do the same thing here, but instead of using react-fontawesome, we’ll be using vue-fontawesome.

npm i --save npm i --save @fortawesome/fontawesome-svg-core @fortawesome/fontawesome-free-solid @fortawesome/fontawesome-free-regular @fortawesome/vue-fontawesome

To summarize, we’re installing Fontawesome, two sets of Fontawesome icons, and a package which provides FontAwesome Vue components. Once the packages have finished installing, we need to import them into our project.

First, in App.vue, replace the HelloWorld import with this:

The first statement is importing the main fontawesome library. The next two import statements are using multiple import syntax to extract specific parts of the fontawesome-free-solid and fontawesome-free-regular icon libraries. For the latter, we are also assigning aliases to the imports, since they share names with the solid counterparts. Finally, we use fontawesome.library.add() to make these four icons globally available for all our other components to use.

We could also have just imported all of a library’s icons — with, say, import solid from '@fortawesome/fontawesome-free-solid' — and added all the icons globally. If you know you only need a small set of icons, however, it’s best to just import the ones you need.

Next, let’s go back to StarRating and add one more import:

Similarly to how we imported parts of the icon libraries, we are importing parts of the @fortawesome/vue-fontawesome library — specifically, FontAwesomeIcon and FontAwesomeLayers. Soon, we’ll be using these to render our star ratings. First, though, we need to tell our StarRating component to make these FontAwesome components available to the template, and that’s what we’re doing by adding the components property to our exported object, its members FontAwesomeIcon and FontAwesomeLayers.

With our FontAwesomeIcon component imported, let’s go ahead and update our template:

Inside the container div, we’ve added a new tag: font-awesome-icon. This is our FontAwesomeIcon component, and when Vue renders our app it will take this component tag and replace it with the component’s template, just as the HelloWorld component is being rendered into our default application. We’ve given it a class of “star”, and we’ve also set a property named icon, its value set to “star” as well. This icon property is a prop we are passing down to the Vue component, telling it which icon we’d like it to render.

The official Vue style guide strongly recommends naming custom components using multiple words, as well as naming your components using either all Pascal-case (FirstLetterCapitalized) or kebab-case (dashes-between-words), and I agree with their reasons. For our tutorial, I’ve chosen to use kebab-case, but ultimately it’s just a matter of preference.

Let’s go ahead and render our new component into the App.vue component file:

We’ve added an import for our StarRating component before the other imports (imports are asynchronous, so JavaScript will not execute any code until all imports have been processed, which means we don’t have to import StarRating after our FontAwesome imports). We’ve also removed the import for HelloWorld because we won’t be needing it. In components, we replace HelloWorld with StarRating. Finally, in template, we again swap HelloWorld for star-rating. If all goes well, upon save you should see a single black star rendered just below the Vue logo.

Calculating How Many Stars to Render #

If you played around with the final result at the beginning of the tutorial, you may have noticed three different types of stars: “full” stars, “half” stars, and “empty” stars. This is how I’ve chosen to represent the star ratings for this project.

Before we can render any of that, though, we need to calculate four things:

  • What is the maximum number of stars we should render?
  • How many full stars should we render?
  • How many half stars should we render?
  • How many empty stars should we render?

You may be wondering why it’s necessary to calculate a “maxStars” value. Sure, we could simply calculate the full, half, and empty star values without calculating a separate max value, but I’ve found that it makes the math simpler to just figure out the maximum number ahead of time and use it in calculations later, so that is what I’ve chosen to do.

Let’s update the StarRating component with the necessary code to perform our calculations:

To briefly explain each calculation:

  • maxStars(): We take the maxRating and divide it by the starRatio, then round the answer up to the next integer.
  • fullStars(): We take the rating and divide it by the starRatio, then round the answer down to the next integer.
  • halfStars(): We take the modulus (or remainder) of rating and starRatio, get half the value of starRatio, and compare the two using a ternary operator. If `x` is greater than or equal to `i`, we return one half-star; otherwise, we return no half-stars.
  • emptyStars(): We take maxStars and subtract from it fullStars and halfStars.

Note where we have placed these methods. These are what Vue calls “computed properties”. In other words, when you access these properties, whether in your template or other parts of your code, Vue will return the result of the function you’ve assigned to that computed property.

If you examine the code used for the emptyStars method, you can see that we’re using the other three computed properties to calculate its return value. The other three computed properties, in turn, are calculated based on the value of the props passed in to the StarRating component. If any of the props should change, Vue will recalculate the values of these computed properties, and any rendered data using these computed properties will also be updated; it all happens automatically.

Rendering the Stars #

Let’s see the computed properties in action. Modify the template thusly:

What we’ve done is add a directive to our font-awesome-icon component called v-for. This directive is telling Vue to render a component this many times, just like looping through a list of items. The text inside of the v-for directive is actually specific syntax that Vue will interpret similarly to a for-in loop. Vue lets you enumerate objects and arrays with this syntax, as well as ranges (which is what we’re using in this case).

Be sure to check out Vue’s official documentation on this subject, which shows you more specifically how to work with arrays and objects using v-for.

We’ve also added a key attribute, and you might have noticed the colon in front of it. What is this colon for? This is a shortcut for the directive v-bind, which binds an HTML attribute to a JavaScript expression. The value of key equals "`fs${fs}`", which is a template literal expression. To use ES5, "fs" + fs (which would also work here; I just prefer using ES6 when possible). When Vue reads this, it will parse the expression bound to :key as actual JavaScript.

You can read more about attributes here. If you follow the link, you’ll notice that the Vue examples use v-bind: instead of just the colon. That is the “full” way to write out binding syntax, but Vue allows you to use just the colon as a shortcut.

Why do we need key? Vue strongly recommends that you add a unique key to each item rendered by a v-for loop because it helps Vue track each item in its virtual DOM, which ultimately improves performance. The expression set in key will generate a string with the incrementing value of the variable fs (set in the value of v-for), which is enough to make this key unique. Since, technically, it isn’t required, we could choose to leave the key out, but it’s good practice to always add a key attribute when using v-for.

So what does all this actually do? If you’ve saved this code, you might have already noticed that the demo app in the browser has already updated to show two black stars instead of one. This is because of our v-for directive, fs in fullStars. The default prop value for rating is 5, and our default starRatio is 2. Those two props are used by the fullStars computed property to calculate its value, and in this case the result is 2. v-for then loops n in 2, resulting in rendering the font-awesome-icon component twice. Again, this happens automatically. You don’t have to write a separate function to handle the looping and rendering for you. Vue just takes care of it because you told it to via the v-for directive.

Now that we know how this works, let’s go ahead and add the template code to render our half stars and our empty stars:

The process for rendering our half stars and empty stars is nearly identical to the process for rendering full stars. We just add a FontAwesome component and use v-for to render as many of each component as dictated by the related computed properties. There are a few differences, however, which I’ll go over briefly.

In both cases, we need to generate unique keys for the key attribute, and to accomplish this we just change the variable to match what we use in the v-for directive and alter the string prefix. For the empty stars, "`es${es}`", and for half stars, "`hs${hs}`".

For the empty stars icon component, instead of just passing in an icon attribute, we’re binding the attribute to a JavaScript array: ['far', 'star']. This is because of the font-awesome-icon component’s interface. By default, passing in a simple icon attribute will render an icon from the solid library of icons, which is what we used to render our full stars. For empty stars, however, we want to render a different icon; specifically, one from the regular library that looks like the empty outline of a star. In order to tell the font-awesome-icon component to render an icon from the regular library, FontAwesomeVue expects us to pass in an array with two members. The first item is the abbreviation of the library we want to pull the icon from, in this case far; the second item is the name of the icon we want, in this case star. Since we’re passing in an actual array, that means we need to bind icon so we can send the configuration array to the component.

You could use ['fas', 'star'] to render our full star icons, instead of relying on the component’s default assumption, if you prefer.

The most significant difference is with how we’re rendering the half stars. Instead of a single font-awesome-icon, we’re rendering two, and we’ve wrapped both components with a font-awesome-layers component. This is because FontAwesome 5 (the version this tutorial is using) doesn’t have a “half-filled” star icon; instead, it has a literal half of a star: one that is “filled” (from solid), and one that is “empty” (from regular).

To get the half-filled star effect we’re looking for, we need to combine those two icons into one. The official way to do this in FontAwesome is to use Layering; in vue-fontawesome, this means using the font-awesome-layers component. Anything within the font-awesome-layers tags will get combined into the same space and be shown as though it were one icon.

Thus, we’ve set the two font-awesome-icon components to use the half-star icons; additionally, we pass in a flip attribute to the empty half-star so it’s reversed. The end result is something that looks like a half-filled star. Excellent!

After I started writing this tutorial, FontAwesome did come out with a half-filled star icon, so we could use that instead of my original solution. I’m not going to change this solution, however, because it also serves to teach about Vue slots — which is coming right up!

Vue Slots #

Let’s take a moment to further examine font-awesome-layers. Up until now, we’ve been using self-closing tags for our components, because it’s simpler to read and we had no need to use opening/closing tag syntax. With font-awesome-layers, however, we’re not only using opening and closing tags, we’re including other components inside of the tags. This is using an aspect of Vue components called slots. To explain what slots do, let’s use a quick example:

The above code (assuming path names and whatnot) results in rendering the following:

In the first component, called ExampleComponent, we basically have two parts: an h2 with the text “These are my children:”, and a ul containing a slot tag. What is this slot tag for? This is telling Vue that anything which is slotted into this component should go here. What does slotting mean, though? To answer that, let’s look at the second component.

The second component is called ExampleParent. In it, we have an h1 with the text “I’m the Parent”. What comes next is our first component, example-component, but in between the opening and closing tags of example-component are three li tags, each containing a human name. If you look at the results image, you’ll see that it renders “I’m the Parent” (from ExampleParent), followed by “These are my children” (from ExampleComponent), and lastly by the names (from ExampleParent). Vue is taking the li tags we enclosed within the example-component tags and inserting them in place of the slot tag we put in ExampleComponent. That is slotting.

If you’d like to follow along, you can copy-paste the code snippets into your components directory as separate Vue files, and then import ExampleParent into App, just like we did with StarRating. Don’t forget to remove it when you’re done with it!

Now that we have a better idea of what slots are, let’s look at the font-awesome-layers component again:

We are slotting two font-awesome-vue icons inside of the font-awesome-layers component. That layers component will then render FontAwesome’s layers container (basically a div container and some classes), so we can make those two half-star pieces look like a half-filled star.

Finishing the First Component #

Alright, we’ve added the code necessary to render all of our stars: full, half, and empty. The last thing we’ll do (for now) is add some styling in the style tags at the bottom of the StarRating component. The finished* code should look like this:

Following the steps outlined so far, you should now see the Vue logo with two and a half gold stars rendered beneath it. If you do, congratulations on making it this far! If not, you should review your code and compare it with what I’ve posted. Hopefully that should expose your problem and get you back on the right track. If not, feel free to submit an issue in the project repository!

Did you notice the asterisk on “finished”? There’s one more thing we’re going to take care of later, but we don’t need to worry about it right now.

Assuming things are working, let’s go ahead and pass a prop down to our component. From App.vue:

When you save the file, you should see the rendered stars change. Assuming you passed in a “7”, like I did, there should be three and a half stars rendered — three full, one half, and one empty. Vue took the rating number we passed down to the StarRating component and converted it to the star rating we now see. We didn’t have to do anything other than pass down that prop.

Of course, at the moment we can only change the rating by manually editing our code to change the value of the rating prop. That obviously isn’t a very user-friendly way to change the star rating, so we’re going to want to have an interface for us to enter the prop values we want and have StarRating update in response, as shown in the final result. To do that, we need to build a second component specifically for handling this interface…a RatingInputs component!

Introducing a Second Component #

To begin, let’s create a new file in the components directory, and call it RatingInputs.vue. Add the following code:

First, in the template, we have a single input for the rating, as well as a label for that input, all wrapped in a container div. Then, in the script section, we have the component’s name and our prop definitions (like we had in the StarRating component). Finally, we have the empty style tags at the bottom.

Next, we’ll take advantage of Vue’s form input bindings and wire up our input element to the component’s data:

We’ve added a directive to the input, v-model, and set it equal to rating_. In the script section, we’ve added a data function, which returns an object containing one property: rating_ = this.rating. What this is doing is initializing rating_ with the value of rating, a prop this component expects to be passed down (and if it isn’t, then it defaults to 5, as we set up in the props section). Because we’ve told Vue to “model” the value of rating_ on our rating input, Vue sets the input element’s value equal to the value of rating_; when we change the value in the input element, Vue then updates rating_ to equal the new value. Thus, Vue gives us two-way data binding without having to do extra work.

Why not just set the input’s value to be rating directly? Technically, Vue would allow us to do that; however, this is considered bad practice. The reason is because anything defined as a prop will have its value changed any time a new value is passed down to the prop via the parent component. Thus, as best practice, if we want to modify a prop’s value from the child component, we should instead create a property in the data object and initialize it with the prop’s value, then modify that data property instead of the prop.

There is no established nomenclature for how you should name your props and data values in cases like these. I’ve chosen to use rating as the prop name for easier reading when passing it in from the parent, and rating_ because Vue doesn’t allow you to start data fields with underscores, and this seemed the next best thing.

Rendering the Input #

Although our RatingInputs component is wired up with the rating input, we still don’t have a way to tell the StarRating component what that input’s value is. To do that, we’re going to need to use Vue’s events system. We’ll start by updating our RatingInputs component:

We’ve added another new directive to the input element: v-on. This tells Vue to listen for an event (it can be a browser or custom event) emitted by this element. :input tells Vue which event to listen for, and "handleRating" is the callback we want Vue to run on this event. In the script section, we’ve added a new property to the component object, called methods. This is where you store any functions you want your component to have access to.

You should use regular functions here instead of arrow functions. Vue automatically handles binding a component’s this to its methods, but it can’t do so for arrow functions because those use the this value of the calling function — which, in this case, won’t be the RatingInputs component, but Vue’s handler for methods.

In methods, we’ve added one function: handleRating, which does two things: first, it gets the value for rating_ from the component via destructuring assignment; second, we call this.$emit, which is a special component function to emit a custom event that only a direct parent component will be able to read. This $emit function takes, as its arguments, a string “rating-update” and an object literal set to {rating: rating_}. rating-update is the name of our custom event, and the object literal is an argument that will be passed in to any callbacks the parent App component has listening for the rating-update event.

Now, in App, let’s make some changes to listen for our custom event:

In the template section, we’ve removed the hard-corded value for :rating and changed it to be the value of the rating data field, which we add in the script section. We’ve also added the rating prop to our RatingInputs component, as well as @rating-update, the custom event that we’re listening for, and a handleRatingUpdate callback.

@ is Vue shorthand syntax for v-on:

We’ve added a methods object to the App component object, as well as the function handleRatingUpdate. It takes one argument, data, which is equal to the object literal we passed into the $emit function in the RatingInputs component. From data, we extract the rating property, and then set this.rating (the data field in App) to equal rating. Upon saving the file, we should now be able to edit the value of rating input element and update the rendered stars in real-time. If you’re able to do so, congratulations!

Adding the Other Inputs #

While playing with the ratings input, you’ll likely notice that you can add a higher input than 10, and a lower input than 0. While this doesn’t seem to affect anything visually, this is not ideal behavior. We want to limit the input so that the user can’t add a higher rating than the maximum, or a lower rating than the minimum. Also, it would be nice to be able to change the star ratio, or how many stars get rendered per rating point (e.g. render one star per rating point, rather than one-half). Let’s get on that.

Let’s start by adding additional inputs for the values outlined above: maxRating, minRating, and starRatio. The code for both RatingInputs and App is as follows:

As you can see, the majority of we needed to do is replicate the code we added to wire up rating, changing only the names. We use the same handleRating callback to process any change to the inputs and pass them up to the parent, and likewise handleRatingUpdate updates all the data fields at once. We then pass back the data in App as props to both StarRating and RatingInputs, and each component updates its own data accordingly.

There are a couple of additional changes. First, all of the input elements have min and max attributes set, which will show an error highlight should any of the values go below the minimum or above the maximum. There’s also a limit property, which is used to constrain minRating and maxRating; this is mainly to control how many stars can actually be rendered, as rendering more than a thousand begins to negatively impact performance.

Better Validation #

We still haven’t solved the problem of preventing someone from inputing illegal values into our data. There are a variety of conditions we’ll need to check, and we’re going to need to check them for both StarRating and RatingInputs. It seems like it would be a good idea to write a separate file that contains all this validation code, which we can import into whatever files need to use it.

Conveniently, I’ve already written such a library for the React version of this project. Since we’re validating the exact same set of data, we can just take that file as-is and plop it straight into our Vue project.

In your src directory, create a new directory and name it lib, then create a file called validate.js and copy-paste the following code into it:

The function we’re most interested in is the default export, which is a function that runs all the other validation functions in the file, returning false if any one of the checks fail, and only returning true if all the checks pass. All we have to do is pass in our data values.

We have the validation library, but now we need to integrate it with our app. Let’s start with the RatingInputs component.

The only place where we needed to make changes was the script file. First, we import the library. Then, in the methods section of the component, we’ve added a new method: anyAreEmpty. All this does is check any arguments passed into it and return true if any of them are equal to an empty string. In our handleRating method, we then use anyAreEmpty to check each of our input values to make sure they aren’t empty strings. Why did we do this? A more detailed explanation can be found in this section of the React tutorial, but the gist is that without doing this, there are scenarios where Vue (and React) won’t let you update the inputs at all.

Finally, we’ve wrapped our call to $emit inside of our validation function, inputIsValid, which takes all of our data values as an argument. We’ve also moved our number conversion to occur before we run the validation function; otherwise, we’d be passing strings into the validation functions, which are expecting numeric values. Only when the validation function returns true do we emit the rating-update event.

With RatingInputs taken care of, let’s turn to StarRating and make a small change there (this is what the asterisk from earlier was for).

Here, we’ve added a new property to the component, called beforeMount. This is one of Vue’s lifecycle hooks, which are basically functions Vue calls at specific stages of a component’s life. In this case, beforeMount will be called once, right before the component is rendered for the first time. We’re checking to see if our default props, being passed in from App, are valid, and if they aren’t we throw an error to let the developer know that they need to check the values being passed as props.

You might be wondering: Why bother with this validation at all? After all, this validation check isn’t what’s showing the errors to the user; the browser is handling that. All this is doing is preventing the rating-update event from being emitted when an illegal value is entered. But that’s the point: without this validation, Vue would emit the event, try to process the illegal values, and then error out in the process. We’d be wasting processing effort doing something we already know is not going to be valid. While that’s not as significant an issue for a small demo app such as this, there are plenty of cases where this would be a costly error. For example, say our update event triggered an AJAX request; we wouldn’t want to send an HTTP request whenever an illegal value is entered. By making sure we only update when our input values are legal, we ensure our code isn’t wasting resources and processing power.

While I’m not going to do this here, we could also use our validation library to trigger more specific error messages in response to the illegal inputs. Feel free to add this yourself, if you’d like!

Final Touches #

With this, all that’s really left to do for RatingInputs is add some styling. If you want to fully match the way my version of the app looks, add the following style section to RatingInputs:

We should also change the styling on App so that the visual structure looks better (up until now we’ve been using the default styles that were generated by Vue when we created the app). I also made slight changes to the App template. To match my version of the app, add the following style section to App and modify the App template to match mine:

Of course, if you want to style things differently, feel free to do so!

Conclusion #

Hopefully this was a fun app to build. I liked making a demo app that wasn’t a todo list. Vue felt intuitive to me, as a web developer, and I loved being able to use template files to keep everything relating to a single component in one file. In exchange, you do have to structure your app in a more specific way, but since I mostly agree with how Vue wants you to do things, I don’t consider this a bad thing.

If you want to view the entirety of my code, look up the project on my Github repo.

Questions? Feedback? Leave a comment!

Sample Project: Star-Rating (React)

This is part one of a multi-part series about React and Vue.
Part 1: React
Part 2: Vue

Lately, I’ve been learning React, a JavaScript front-end framework. As of now, it is one of the most popular JS frameworks in existence. To help myself learn the framework, I built a sample project: a Star-Rating app. It functions similarly to what you might see on Amazon, where you have a rating represented as a line of stars. You can change the parameters used to calculate the star rating via an inputs component.

To see the final result, click this link.

I think it turned out rather nicely, and today I’d like to show how I built it, and in the process explain how React does things, as best as I currently understand it.

This tutorial presumes a basic knowledge of HTML, CSS, and JS, along with some basic knowledge of how to develop using a command line interface (or CLI) and how to use Node Package Manager (or NPM). If you’re unfamiliar with any of these things, feel free to make an online search for whatever you don’t know.

Table Of Contents

Setting Up
Looking Around
Creating Our First Component
Rendering Stars with FontAwesome
Calculating How Many Stars to Render
Rendering the Stars
Adding Our New Component
Introducing a Second Component
State and React
Passing State Between Components
Wiring Everything Else Up
Better Validation
Bug Hunt
Final Touches
Conclusion

Setting Up #

To start the process, I chose to use create-react-app to handle creating the base project structure. You can get it through NPM. Using the command line:

# Install create-react-app. You only need to do this if you don't already have it installed.
npm i -g create-react-app

# Create a new React single-page app.
create-react-app react-star-rating

# Navigate to the app directory and fire up the development server.
cd react-star-rating
npm start

After performing the above instructions, a tab should automatically open up in your default browser to localhost:3000, which should be a page containing a spinning React logo and some additional text.

It should be noted that you don’t need to use create-react-app to make a React project; instead, you could just include CDN links of these two scripts in an HTML file:

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

I find create-react-app offers conveniences that are useful, such as hot reloading (changes are updated as you save your files) and a development server (so I don’t have to set one up myself), so I usually prefer to use that. This tutorial will assume that you are also using create-react-app.

Looking Around #

Now that we have the barebones project set up, let’s open the project directory in a code editor. You can use whatever editor you wish; I personally use the free editor Visual Studio Code, but there are plenty of other excellent options, such as Atom and (if you’re willing to spend money) Sublime.

Once you have the project open in the code editor, you should see there’s a bunch of files already set up. Let’s look in the src directory and open up the file called App.js. It should look something like this:

One thing you’ll notice right away is the use of import and export statements, as well as the use of classes. These are all part of the ES6 syntax. React makes heavy use of ES6 features; if you’re not familiar with ES6, here is a quick guide of basic features. Not all ES6 features are yet included in modern browsers (as of this writing), so one of the things create-react-app provides is a “transpiler”, which automatically converts ES6 syntax to its ES5 equivalent, so browsers know how to read the code. If you want to work with React, I’d recommend becoming familiar with ES6 features and how to use them; once you know how it works, ES6 lets you do really powerful things.

I’ll occassionally point out instances where I’m writing ES6 and compare it to the ES5 version so you can see how much simpler ES6 can make things look.

So, what is the code for App.js actually doing? Let’s do a brief examination.

These import statements are including external files into our file. We can even use imports to add specific parts of a file to our app, which is what { Component } is doing. Notice that we can import more than just JavaScript; we’re also including a logo image (logo.svg) and our app’s CSS file.

Here, we are using an ES6 feature — classes — to extend the Component class, which means we are getting access to all the functionality that a Component class has. If we were to use ES5 syntax, we wouldn’t be using class syntax at all. Instead, we’d be calling a React function called createClass, like so:

Both this snippet and the one previous do exactly the same thing: create a new React Component class.

So, what is the “render” function for? Primarily, it is responsible for rendering our component’s HTML. You might have noticed the HTML elements being returned by the render function:

Strictly speaking, this isn’t actually “HTML”. It’s something called “JSX”. The React site gives a good explanation of what JSX is, but to summarize, it’s a way to write HTML markup using JavaScript. This is one of React’s biggest features: the idea that components return their own HTML to render on the page. Some people really love the idea, as it allows you to keep the logic and markup of a component in the same file, which can make it easier to reason about an app’s logic. The JSX makes it easier to understand what the component’s markup looks like. React takes care of converting JSX to rendered HTML for you.

Some say that you shouldn’t mix JavaScript and HTML/JSX together. If you belong to this camp, then you don’t have to use JSX at all. Everything you can do in React using JSX, you can also do through pure JavaScript. The following code does exactly the same thing as the previous snippet, but just using JavaScript:

As you can see, under the hood JSX is just a series of JavaScript functions and objects, which end up creating our HTML elements. Personally, I find this syntax more difficult to read, and thus harder to reason with when I’m building an app, so I like to use JSX. That’s what I’ll be using for the remainder of this tutorial.

There’s another point of interest we should look at in the JSX code: the {logo} which is being set as the image tag’s source. In JSX, if you want to use JavaScript variables, you can do so by adding that variable directly to the JSX code, enclosing it in curly brackets. This is what will allow us to show various bits of data that we calculate with JavaScript.

Finally, at the end of the file, we have one final line:

As we use import to pull stuff in from other files, we use export to send stuff to other files that want to import our code. In this case, we are exporting the App component class.

Now that we’ve analyzed the App.js file provided by the boilerplate code created with create-react-app, and in the process familiarized ourselves a little bit with how React works, let’s start actually creating our app!

Creating Our First Component #

First, let’s make a folder called “components”, which will house all of our component files. With our components folder created, let’s add a new file to it: StarRating.jsx. Note the .jsx extension. It signifies that we are using JSX in this file. You could, technically, just make it a regular .js file (and, if you noticed, the file we looked at earlier is App.js), but I prefer to use the .jsx extension because it helps me know which components are rendering HTML.

Now that we have our first component’s file, let’s write some code.

This is just adding some code to get us started. We import React and the Component class, and we export a new class, StarRating. I’m defining the class as part of the export, instead of creating the class first and then exporting it, as we saw in App.js. Either way works; I prefer to use this method. We also create a render function and return a single <div>, with a class called star-rating. Note that, instead of class, we use className. Since JavaScript itself uses the word “class”, when writing JSX we need to distinguish between an HTML class and a JavaScript class, and this is done by using className when writing an element’s classes.

You may notice that I’m not using semicolons when writing my JavaScript. In many cases, the browser takes care of adding the semicolons you need, so you don’t actually need to write them yourself. This is just a personal preference I have; you can choose to write or not write semicolons, as per your own tastes.

The other thing we’ve added is some default props, which React requires you store in an object assigned to the static property defaultProps. What are props? They are the data that gets passed in by a parent component, and the child component can then take that data and use it as it sees fit. In a bit, we’re going to modify the App component to do just that, but until then, we’re going to use these default values. It’s also good practice to include default values, as it helps show what props your component is expecting.

Here is a quick explanation of what each prop is for:

  • minRating: This controls the lowerbound value of our rating. Defaults to 0.
  • maxRating: This controls the upperbound value of our rating. Defaults to 10.
  • rating: The actual value of our rating. Defaults to 5.
  • starRatio: This controls how many rating points it takes to render a full star. Defaults to 2, which means it takes a rating of 2 to render a single star. With a default rating of 5, this will result in rendering two and a half stars.
  • limit: We’ll use this to set a limit for how large the min/max rating values can be. This is purely to improve app performance.

Rendering Stars with FontAwesome #

Next, we need to add some code that will allow us to render stars. To do this, we’re going to install a font library called FontAwesome, which has thousands of custom icons stored as scalable SVGs. This way, we can style our stars however we want. Specifically, we will be using the react-fontawesome package, which integrates FontAwesome with React.

First, we’re going to install a few libraries via NPM and save them to our package.json:

npm i --save @fortawesome/fontawesome @fortawesome/fontawesome-free-solid @fortawesome/fontawesome-free-regular @fortawesome/react-fontawesome

To summarize, we’re installing Fontawesome, two sets of Fontawesome icons, and a package which provides FontAwesome React components. Once the packages have finished installing, we need to import them into our project.

First, we need to go back to App.js and add a few lines:

The imports work just like our previous import statements. The line fontawesome.library.add(solid, regular) is a function of fontawesome which will take the function arguments and, if they are valid fontawesome icons or sets, make them globally available to all our other components (so we don’t have to individually import the icons in each component file). In this case, we’re importing all of the “solid” and “regular” icons and making them globally available. We could also, if we wish, pull individual icons from each set (like we did with React’s Component) and add each one to our library. This results in slightly improved performance; however, since this is just a simple project example, I’m going to add the entire solid and regular sets of icons to the library.

Next, let’s go back to our StarRating component and add one more import:

Here, we are importing the FontAwesomeIcon component. We will be using it to render our star icons. (Confused? Just keep reading, for now; there will be examples that should hopefully make things clearer.)

Calculating How Many Stars To Render #

If you played around with the final result at the beginning of the tutorial, you may have noticed three different types of stars: “full” stars, “half” stars, and “empty” stars. This is how I’ve chosen to represent the star ratings for this project.

Before we can render any of that, though, we need to calculate four things:

  • What is the maximum number of stars we should render?
  • How many full stars should we render?
  • How many half stars should we render?
  • How many empty stars should we render?

You may be wondering why it’s necessary to calculate a “maxStars” value. Sure, we could simply calculate the full, half, and empty star values without calculating a separate max value, but I’ve found that it makes the math simpler to just figure out the maximum number ahead of time and use it in calculations later, so that is what I’ve chosen to do.

The following is the StarRating component, with the addition of the code which will calculate the four values we want:

To briefly explain each calculation:

  • maxStars(): We take the maxRating and divide it by the starRatio, then round the answer up to the next integer.
  • fullStars(): We take the rating and divide it by the starRatio, then round the answer down to the next integer.
  • halfStars(): We take the modulus (or remainder) of rating and starRatio, get half the value of starRatio, and compare the two using a ternary operator. If `x` is greater than or equal to `i`, we return one half-star; otherwise, we return no half-stars.
  • emptyStars(): We take maxStars and subtract from it fullStars and halfStars.

ES6: When you are declaring methods inside of an object or class, you can use the shorthand notation yourFunction () {} instead of explicitly specifying yourFunction: function () {}. Also, I’m assigning the values of the props to variables within the calculation functions using ES6 destructuring, which is a convenient way to get values off of objects; in ES5, you’d have to use objectName.dataValue.

Rendering the Stars #

Now that we can calculate how many of each type of star we need to render, let’s get to actually rendering them! First, let’s render the fullStars. In our render function:

The first thing we do is assign fullStars to equal the result of our fullStars() function. Next, we create a new function within the render method, called renderFullStars(). Since we’re defining this within a class method, and not the class itself, we can’t use the shorthand notation from before; we have to explicitly assign the function.

ES6: I’m using an arrow function, but I could also have simply declared function renderFullStars() {}. Either way works; I prefer the arrow function syntax here because it looks cleaner to me.

The code in renderFullStars() may seem confusing, at first glance, especially if you’re not familiar with the various methods associated with arrays. However, once you know how it works, I think it’s actually easier to read.

First, we check to see if the number of full stars is 0. If it isn’t, then we proceed to create an empty array with the length set to the number of full stars. Using chaining, we then call fill() on the resulting array, which will fill the entire array with whatever value we want; in this case, null. Finally, we use the map() method to create an entirely new array, with exactly the same number of items, but instead of being null these items equal the result of the callback function we pass in (note I’m again using an arrow function). This final array is what gets returned. What if there are no full stars? In that case, we return an empty string; you’ll see why in a moment.

Let’s take a brief moment to examine the callback we’re passing into the map method:

Remember the FontAwesomeIcon component we imported earlier? We are now using that component as the return for our callback. We’ve given it a class of “star” (via className), which our CSS can target later. The next two things we are setting are props which we are passing to the FontAwesomeIcon component. I’ll go over each one.

The first prop we’re setting is key. This is something React uses to help keep track of lists of items, and while it is technically possible to exclude the key property from a list, it is strongly discouraged. The key should be a unique value, and to accomplish this I’m using the string “fs” plus the i argument, which is equal to the index number of the current array item. Note that, since we need to use a JavaScript expression to set the key value, we enclose it in curly brackets.

ES6: I’m using a template literal to set the value of the string, which uses the back-tick character ` instead of regular quotation marks. The ES5 equivalent is "fs" + i.

The second prop is icon. This tells the FontAwesomeIcon which icon we want to use. For full stars, we want to render star from the solid library.

At the end, we self-close the component. Generally, you can treat React components like self-closing tags, but you can also use <YourComponent></YourComponent> instead. There are cases where we’d want to use the opening/closing tag syntax, but this isn’t one of them. Generally, I prefer to use the self-closing tag format because it’s simpler to read.

Finally, in the return…

… we’ve added {renderFullStars()} inside of the <div>. Since curly brackets enclose JavaScript expressions in JSX, that means we’re running the renderFullStars function and outputting the return directly into the JSX. Take a moment and go look at the final result again. The default rating here is set to 5, which means two full stars and a half star are rendered. renderFullStars() creates two FontAwesomeIcon components and outputs them into the star-rating container, which is then rendered into HTML by React. What if there aren’t supposed to be any full stars? Then this function returns an empty string, and nothing is rendered.

Let’s go ahead and add the code to render half stars and empty stars:

As you can see, the process for rendering half stars and empty stars is the same as for full stars: pull in the calculated values, create render functions to render the components, and run the render functions in JavaScript expressions in the JSX. The only differences lie in the FontAwesomeIcon components we are returning.

For empty stars, there are two differences:

  • We’ve changed the key to use “es” instead of “fs”. This is to keep the key unique from the keys we generated for the full star components.
  • Instead of passing in a string for the icon, we’re instead passing in a JavaScript expression. This is because, by default, the FontAwesomeIcon assumes we want an icon from the solid library. Our star icon for full stars was part of the solid library, so we could just pass in the name of the icon. But for empty stars, we want to use the star icon from the regular library, so, as per the react-fontawesome documentation, we need to pass in an array. The first item in the array is the library we want to use, “far” (“FontAwesome Regular”); the second item is the name of the icon itself, “star”.

For half stars, we also use a different key prefix, “es”. But, instead of returning a single FontAwesomeIcon component, we’re returning two different icons, wrapped in a span. The reason for this is because of the way FontAwesome renders the half-star icons. Instead of rendering a single icon of a star half-full and half-empty, FontAwesome has a full half-star and an empty half-star.

To get the half-filled star effect we’re looking for, we need to take advantage of FontAwesome’s power transforms — specifically, Layering. What Layering lets you do is take two icons and combine them together so they appear as a single icon. You do this simply by adding the fa-layers class to an element containing the icons you want to combine.

So we’ll use the two half-star icons — star-half from “solid” and {['far', 'star-half']} from “regular”. We’ll also pass in flip="horizontal" to the regular half-star so it’s reversed. The end result is something looks like a half-filled star. Excellent!

At this point, we’ve finished* the StarRating component! Here’s what the code looks like:

Our component takes in a bunch of props, uses the values of those props to calculate how many star, empty star, and half star icons to render, and then returns the rendered stars in JSX. It’s time to go back to the App component and add our brand-new component!

Did you notice the asterisk on “finished”? There’s one other thing we’re going to address later, but we don’t need to worry about it right now.

Adding Our New Component #

To begin, let’s import the StarRating component and add it to our App component’s render return:

If you don’t have the local development server running yet, do so now by entering npm start into your CLI; if you do have it running, then upon save the page should automatically reload. At this point, you should see a row of black stars appear beneath the default text — two full, one half, and two empty. If you see this, congratulations, you’ve just rendered a React component! If you don’t see this, or if you get an error, try to go back over your code to make sure it matches what I’ve previously wrote; hopefully you’ll find what the problem is and fix it.

Assuming things are working, let’s go ahead and pass a prop down to StarRating:

Upon saving the file, you should see the rendered stars change. Assuming you passed in “7” like I did, you should now see three and a half stars. This is the power of props: a parent component passes the props down to the child, which then takes the props and automatically updates any data that is calculated using those props. In our case, we passed down a rating of 7, and StarRating converted that rating into full-stars, half-stars, and empty-stars and updated the rendered result automatically.

Of course, right now we can only update the rating by manually changing the value of the rating prop being passed to StarRating. That’s not very practical at all. What we want to do is have a way for us to input the values we want and have StarRating update accordingly, as seen in the final result. To do that, we’re going to need another component specifically dedicated to do just that…a RatingInputs component!

Introducing a Second Component #

Let’s start by creating a new component file in our components folder, calling it RatingInputs.jsx. Add the following code:

Just like with StarRating, we start with importing React and the Component class from the “react” package, then export a class, this time called RatingInputs. The class includes a render function which returns some JSX, as well as the same set of default props we used for StarRating.

I took the liberty of going ahead and including an input tag (and corresponding label) for our rating. Notice the use of htmlFor on the label instead of the usual for; like class, for is a reserved word in JavaScript, so JSX provides an alternative for the HTML attribute.

In case you’re wondering why you aren’t seeing this show up on the page, remember that RatingInputs hasn’t yet been imported into the main App component. You could do so now, if you wish. You just might get some errors flashed to the page as you make changes to the code.

As of right now, the rating input isn’t wired up to anything; it’s just a dumb number input element. To remedy that, let’s begin by pulling the rating prop into our render function and setting the input’s value equal to it:

Notice that I’ve added an attribute called “ref” to the input. What’s that for? This is how we’re going to tell React what element our rating input is. I’ve also added an attribute called onChange; this is, in fact, an event handler. The way React/JSX handle event handlers is different from using your typical addEventListener(), and you can read more about it here. The value of onChange is set to a JavaScript expression: this.handleRating. That will call a method on our RatingInputs class called handleRating.

Wait, we don’t have a method called handleRating? Let’s fix that:

Currently, all our handleRating function does is save the value of this.refs.rating.value as a number, but we’ll change that soon. The other change is the addition of a constructor function to our class. In other programming languages, constructor functions are run every time a class is constructed, and here is no different. We call super() to call the parent class’ constructor (Component), and after that we bind the this value of our handleRating function to the this value of our class.

Why are we doing this? Well, when we run a callback function in our JSX, the this value of the callback function will be undefined. Thus, we need to explicitly bind the value of this in the callback function to the this of our class so we can access this.refs.

Now we have a callback function that will run every time we update the value of the rating input. How are we going to send that value from the RatingInputs component to the StarRating component? By passing it up to the parent App component and having it pass the value down to StarRating.

State and React #

Before we implement the code that will transfer our rating data from RatingInputs to StarRating, we need to discuss the concept of state in React. A fundamental concept powering React is the idea that no child component should ever modify any prop passed down to it. Doing so would mean the parent component’s state could be modified in a way the parent doesn’t control. When that happens, you can’t always be sure what is modifying the state.

Instead, it is the responsibility of the parent component to provide the child component with the means to request changes to the parent’s state. That way, you know the only way the parent’s state can be modified is through methods the parent itself provides. The parent then passes the updated state back down to the child component, as well as to any other components receiving props from the parent.

With that in mind, we can have App pass one of its own methods down to the RatingInputs component that, when run, will update the state in App. Since StarRating also receives that same state from App, it will receive the changed data from App as soon as it is updated. Thus, we preserve the sanctity of the state by not allowing RatingInputs to modify it directly; instead, RatingInputs asks App to update its state by calling the specified update request function, and App handles changing its state and passing the updated state down to both RatingInputs and StarRating.

Enough theory, let’s code.

Passing State Between Components #

First, in RatingInputs, we’ll add the following to handleRating():

This will call a function passed to RatingInputs as a prop, called onStarRatingsUpdate.

Next, let’s update App:

Whoa, there’s been quite a lot of code added! Let’s break it down, piece by piece.

First, we added an import statement for our RatingInputs component. The next addition is a constructor for our App class:

Once again, we call super() to run the Component class’ constructor, and we also bind the this value for a function called this.handleStarRatingsUpdate, similarly to what we did for handleRating(). Finally, we set a property called state to be an object, with one member, rating, set to 5. This state property is how components handle state within themselves. We will be passing this state down to both StarRating and RatingInputs via props.

Confused about the difference between “props” and “state”? Props are data that flow from a parent component to a child; state is the data within a component.

Next, we add a function called handleStarRatingsUpdate:

In React, outside of the constructor, the only way state should be modified is by calling a component’s specific setState function, and this is what we’re doing here. We’re passing in an object to setState, and setting the properties of the object using ES6’s spread syntax. Basically, the spread operator will take all the properties of one object and copy them over to a different object. In this case, we’re first taking all of the values in this.state (the App component’s state), and then we’re taking all the values from the data argument and adding them to the object being passed into setState. This results in any properties from data overwriting any similarly-named properties pulled in from this.state.

Still confused? Keep reading; there will be a demonstration of what this accomplishes, and hopefully that should clear things up.

Spread syntax also works with arrays! Read the reference link to learn more.

Lastly, we update our render function:

We’re pulling in rating from this.state. We’ve also replaced the hard-coded prop being passed into StarRating with this rating value. Finally, we’ve added our RatingInputs component below StarRating, and we’re passing two props to it: rating and onStarRatingsUpdate, which we’ve set equal to our function handleStarRatingsUpdate. Why the two different names? It’s just a convention: we say “on” to refer to the prop, and “handle” to refer to the actual function which handles the call from the child component. We could easily have both the prop and the function be the same, if we wanted. My preference is to use the on/handle convention.

Assuming nothing went wrong, once you save App.js you should see the rating label and input appear immediately below the black stars from StarRating. Try modifying the value of the input. If everything was done correctly, as you change the value of the input, the rendered stars should also update right along with it. Our components are talking to each other through the parent!

If you were confused by the contents of handleStarRatingsUpdate(), perhaps now it’ll make more sense. When we update the rating input, it calls handleRating(), which takes the value of our rating and passes it as an argument into onStarRatingsUpdate(). This runs handleStarRatingUpdate(), on App. It calls setState(), which first sets state equal to this.state (in other words, the previous state values). Next, it adds any values passed in via data; any state properties with the same key as the properties passed in by data get overwritten with the value from data. With the state updated, App passes the state back down to both RatingInput, where the value of the rating input is updated, and StarRating, where the updated rating is calculated as stars and rerendered onto the page.

As you play with the rating input, you may find you’ve triggered an error called “invalid array length”. This is because we’ve set rating to a value lower than minRating or higher than maxRating, and our star calculations can’t handle that. To prevent us from setting the rating too low or too high, let’s start by setting the min and max values on our rating input:

Now, when we toggle the rating input up and down, we should be stopped when our rating gets down to 0 or up to 10. That’s good enough, for now; we’ll be implementing a better fix shortly.

Wiring Everything Else Up #

Now that we have our rating wired up, let’s go ahead and wire up minRating, maxRating, and starRatio. When you’re done, your App and RatingInputs components should look something like this:

We’re setting the min values of both minRating and maxRating to 0, and the max values to limit. You technically don’t need to include a limit, but in testing I’ve found that adding min/max ratings resulting in over 1,000 rendered stars introduce the possibility of performance issues. Thus, I made the decision to limit how high those values can be increased.

Now all of the values are dynamic: we can set the maxRating to 20, our starRatio to 1, our minRating to 5…any number of combinations, really! As you experiment with the possible combinations, however, you might notice something: if you directly set the input values to something illegal (instead of using the increment/decrement buttons), you’ll trigger the “invalid array length” error. While setting the min/max attributes of rating stops the input increment/decrement buttons from going out of range, they do not prevent us from entering such an illegal value directly. Also, you could change minRating to be higher than maxRating (or maxRating lower than minRating), and trigger an error that way.

We clearly need better validation than what we can get from HTML. Let’s implement it!

Better Validation #

First, we’ll create a new folder in src and call it lib. We’re going to make a library of functions we can use to validate our inputs. Make a new file in lib and call it validate.js, then place the following code into it:

With ES6 exports, you are not limited to only exporting one function; you can export as many as you want. You just have to refer to them explicitly by name when you pull them out. For example, if you wanted to use the minLessThanMax function, you’d write the import statement as import { minLessThanMax } from 'path/to/validate'. You can specify a single function as the default export; this is what will be returned if you simply do import ThisFunction from 'path/to/validate'. In our case, all we really need is the default function in validate. I just wanted to illustrate what export is capable of, and that you aren’t limited to one export per file.

Let’s look at the default function we’re exporting. We’re taking in arguments for rating, minRating, maxRating, starRatio, and limit, and then passing these arguments into various validating functions. The key is that we’ve strung the return as a chain of functions using the && (and) operator. The moment any one of these validating functions returns false, the entire function returns false; otherwise, if all the validating functions return true, the function returns true.

For a couple of the validating functions, I use a combination of rest parameters in the function argument and the filter array method to validate one or more possible values with just a single line of code. Read up on the two links to figure out how this works!

Now that we have our validation library, let’s start by importing it into RatingInputs:

As you can see, all we needed to do is import the default validate function as inputIsValid, and then wrap our call to onStarRatingsUpdate() in an if statement which checks to see if inputIsValid() returns true. If it doesn’t, then nothing happens. The inputs won’t update, which means you can’t change them to anything which would cause validation to fail.

We also need to import our validation library into StarRating (this is what the asterisk was for):

Here, we are once again importing the validate library as inputIsValid. This time, we’re using a new function called componentWillMount to run the inputIsValid check, and if it fails we throw an error.

What is this for? componentWillMount() is a part of how React components work, one of the so-called “lifecycle methods”. A lifecycle method is just a function that a React component runs at a specific moment, such as before props are passed down, or before/after a component is rendered. In this case, we are using the componentWillMount lifecycle method, which runs right before a component is first rendered. Because we are checking inputIsValid() at this point in time, we can make sure the initial props passed down by App are valid, and if they aren’t we’ll throw an error telling the developer that they need to make sure rating is between minRating and maxRating (as this is what’s causing validation to fail).

If you want to learn more about lifecycle methods, read this.

Bug Hunt #

Now, things seem like they work. If you try to directly input a minRating of 11 when the maxRating is 10, you’ll find yourself unable to do so. Same with if you try to make rating exceed the bounds of the min and max ratings. Yet there is still a bug, which I didn’t notice until I started messing around with the project one final time before submitting this post.

What is the bug? Click on the rating input, then try to backspace. Normally, when you do this, you’d expect the input field to be empty; however, our app will either refuse to delete the value at all, or it will set the value to 0. Peculiar, indeed, and not very user-friendly.

Why is this happening? Well, in our handleChange function in RatingInputs, we automatically convert each ref’s value to a number when we assign it. This is because refs are stored as strings, so we want to make sure we’re working with numbers when we’re performing validation. What happens when an empty string gets converted to a number? It becomes 0. Thus, when we assign the value of an input that was cleared by the user — an empty string — we’re assigning the variable a value of 0. When minRating is 0, this results in rating being set to 0; otherwise, 0 is lower than minRating, so our code doesn’t allow the update to be made.

How do we fix this? We’ll need to refactor the RatingInputs component to have its own state, instead of merely rendering the props App passes down to it. This way, we clear the input fields, but delay sending an update until the inputs have values that are validated. Why wasn’t this done in the first place? When I first designed the component, I didn’t think it needed to have its own state, so I simply wired everything up through props. Now, however, it’s clear that we need the inputs to be able to have values separate from the parent state, so giving RatingInputs its own state is appropriate.

Here is what the changes will look like:

First, in the constructor, we set the initial state of the component to be equal to the props being passed down to it (we also accept props as an argument). Next, we add a new function, anyAreEmpty, which just checks to see if any of the arguments passed into it are empty strings.

We make quite a few changes in handleRating():

  • We change our assignments to get the raw ref values, instead of converting them to numbers.
  • We update the state of our application to match the value of the refs.
  • We use the anyAreEmpty function to see if any of the variables are empty strings, and if so we return.
  • Having verified we have no empty strings, we convert the ref values to numbers.
  • Finally, as before, we pass the numeric values through our validation library, and only update when validation passes.

Lastly, in our render function, we get our default values from the state of RatingInputs, not the props passed down from App.

When these changes are implemented, you’ll notice that you can now set the input fields to illegal values once again. However, no updates are sent to App, so StarRating is not updated. Additionally, because of the min/max attributes set on the rating input, an error highlight appears around the element when an illegal value is set. I consider this “good enough” error notification for a sample project.

Final Touches #

At this point, our Star-Rating app is fully functional and secure against bad data. The only thing left to do (if you want) is to restructure the app and change the styling to make it look like the final result. We’ve already done a lot of hard, good work, so I’ll simply provide you with the JSX you’ll need for App.js and the styles you need to replace within the App.css file to make it match my version of the app:

Of course, if you want to make your Star-Rating app look completely different, then feel free to do your own thing!

Conclusion #

I hope you had fun building this app; I certainly enjoyed doing something different from a Todo list as a sample project. React, once you get used to some of the ways it wants to do things, is a fun front-end framework to build apps with. Even though it may seem like it takes some effort to do things with React, the way it is designed helps you think logically about the structure of your code, helping you avoid writing smelly code and making it (mostly) clear how your app works.

If you want to view the entirety of my source code, look up the project on my Github repo.

Questions? Feedback? Leave a comment!

Star-Rating Part 2: Vue

Creating a Data Container in Javascript

While working on an interactive novel demo, I happened to need a container for containing flags (aka values that I could check later on to change bits of flavor depending on what a player chose), but I didn’t want to just use a plain ol’ JavaScript object. I wanted to create a true data container where you could set any property you wanted, but you wouldn’t be able to overwrite the data in the container itself.

After experimentation and some searching, I came across Proxies, which let you define custom behavior for basic object methods. With guidance from a Stack Overflow answer, I came up with this:

const Flags = new Proxy ({data: {}}, {
    get: (target, name) => target.data[name],
    set: (target, name, val) => target.data[name] = val
});

That was a fun little bit to figure out, and I got to learn something new. Woohoo!

React Error: Expected a string, got object

If you’re working with React, you might run into one or both of these errors:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `SomeComponent`.
bundle.js%20line%20242%20%3E%20eval:45:9
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `SomeComponent`.

One possible problem, which is what happened to me, is that you simply forgot to export one of your modules. In this case, I had a child component which I forgot to export, but the resulting error said nothing about the child component so it took awhile to puzzle this out. Hopefully this helps someone else figure out the problem faster than I!