Challenge: Build a Game of Life React App
Cells are arranged on a 2D grid. Each cell can have two possible states: alive or dead. The cells stay alive or dead based on the following two rules:
- A living cell with 2 or 3 living neighbors will stay alive.
- A dead cell with exactly 3 neighbors will spring to life.
Any cell with more than 3 living neighbors dies from overpopulation, and any cell with fewer than 2 living neighbors dies from underpopulation.
There are a ton of examples online of the Game of Life, so I won’t spend a lot of time discussing the actual coding. I used a pretty basic algorithm that is not at all optimized. The wikipedia article discusses some optimization strategies, but for the FCC Speedrun I am trying to get through these relatively quickly, so I did not attempt to implement any of these algorithms.
What was more challenging than the coding was the styling. I originally got it looking how I wanted using some hacky css stuff. I knew it wasn’t responsive, but I wasn’t too worried about that. Then someone told me it looked wrong in their browser. They were using Google Chrome, same browser as me, so that was a bit puzzling and concerning.
I was able to get the styling mostly fixed, but then I went to add a div containing the instructions for the game and everything broke. My grid was overlaying the instructions and the controls were way out of whack. At that point, I decided to step back take a new approach.
Flexbox to the rescue
I haven’t really worked with flexbox yet. I am familiar with it, and I did a brief tutorial at CodeSchool.com, but that’s it. I decided that this would be a good time to learn it. I had already purchased the Flexbox Tutorial from Udemy, so I decided to give it a go. It’s only two hours long, but covers pretty much everything about flexbox.
Flexbox worked out pretty well. The controls along the top with the two buttons and the lifecycle counter took a bit of fiddling, but nothing too horrible. I discovered that if you want to get a specific item in a flexbox to ‘float’ left you can actually do this by setting margin-left to 0.
For some reason, even though my flex-direction is row and there is plenty of room for the buttons, the two buttons on the right were stacking on top of each other. I was able to fix this by having ‘float: right’ on the button element.
I started out with bootstrap included in this project, but realized I was only using it to style two buttons. Bootstrap is a pretty big library, so using it just for something so simple seems silly. I ended up taking it out. There is no CSS framework used in this project, just pure CSS.
This took me about a week. It was a fun challenge. This is something that I think will be a good addition to my portfolio. It really helped me get an understanding for communication in React apps. I didn’t use Redux in this, so all communication is parent-child communication.
You can view the live app here.
You can view the repo here.