This full project tutorial shows how to create Conway’s Game of Life using React.
You don’t have to know a lot already but it may be helpful to check out one of these videos first to get an overview of React:
https://youtu.be/1rIP81hjs2U (45 min)
https://youtu.be/QqLkkBKVDyM (15 min)
⭐ Code ⭐
💻 Github repo: https://github.com/beaucarnes/fcc-project-tutorials/tree/master/gameoflife
💻 Direct link to JavaScript file: https://github.com/beaucarnes/fcc-project-tutorials/blob/master/gameoflife/src/index.js
💻 Code for just play method (gist): https://gist.github.com/beaucarnes/1c22fc5e10b15a1f2bf338bf7d09b1b9
⭐ Tutorial Outline ⭐
⌨ Part 1: Basic Setup (2:03)
⌨ Part 2: Begin Main Component & CSS (6:56)
⌨ Part 3: Create Grid Component (10:21)
⌨ Part 4: Create Box Component (21:55)
⌨ Part 5: Begin Method Creation (27:02)
⌨ Part 6: Play Method & Game Logic (35:09) [see link for gist above]
⌨ Part 7: Buttons w/ React-Bootstrap (39:08)
⌨ Part 8: Finish Buttons & Main Component (39:08)
👏 Special thanks to these people who helped review the code: Sean Smith, Marius Espejo, & Danny Huang.
🐦 Beau Carnes on Twitter: https://twitter.com/carnesbeau
—
Learn to code for free and get a developer job: https://www.freecodecamp.com
Read hundreds of articles on technology: https://medium.freecodecamp.com
And subscribe for new programming videos every day: https://youtube.com/subscription_center?add_user=freecodecamp
Original source
36 responses to “React Project Tutorial – Game of Life”
Steve Jobs?
Thanks as usual for these tremendous free educational resources. You truly are setting the bar for what the future of education looks like, and it is a bright future filled with students who aren't debt slaves.
Thanks so much.
Did somebody manage to refactor this for speed? I don't think that's possible, as long as every generation requires full blown state update, therefore component update, therefore re-render, therefore width*height number of DOM elements redrawn.
I can see the game being done with OK performance in JS through canvas, but it's not a job for React, but rather graphics oriented library like p5.
Can anyone explain how you would use map instead of a nested for loop?
Here is the play() method code from 36:12 :
play = () => {
let g = this.state.gridFull;
let g2 = arrayClone(this.state.gridFull);
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
let count = 0;
if (i > 0) if (g[i – 1][j]) count++;
if (i > 0 && j > 0) if (g[i – 1][j – 1]) count++;
if (i > 0 && j < this.cols – 1) if (g[i – 1][j + 1]) count++;
if (j < this.cols – 1) if (g[i][j + 1]) count++;
if (j > 0) if (g[i][j – 1]) count++;
if (i < this.rows – 1) if (g[i + 1][j]) count++;
if (i < this.rows – 1 && j > 0) if (g[i + 1][j – 1]) count++;
if (i < this.rows – 1 && j < this.cols – 1) if (g[i + 1][j + 1]) count++;
if (g[i][j] && (count < 2 || count > 3)) g2[i][j] = false;
if (!g[i][j] && count === 3) g2[i][j] = true;
}
}
this.setState({
gridFull: g2,
generation: this.state.generation + 1
});
}
REACT + MOBX tutorial please
This is really amazing lecture I've ever taken ! Thank you a lot and your insight !
Great video, the only small thing is that I'd use stateless functional components for most of these as recommended by FB but this works fine too 🙂
Hey guys, I did this project last weekend and I wanted to ask if someone knows how it would be able to implement a 2. type of cells (for example red ones) which would live in the same game as the normal/green ones but they would have other Game of Life rules than the normal ones.
when you reach at 29:50 . just go back and change the onClick to OnMouseOver to just paint on the canvas. Kids Game 🙂
Why is width = cols multiplied by 14?
Very weird. My code is exactly the same but Grid is not showing up in the browser.
So in case it helps anyone else, to get the DropdownButton to work, I had to use Bootstrap 3, even though the instructions in the react-bootstrap documentation tell you to use the CDN that gets the latest Bootstrap, which currently is 4.
Why not use CodePen?
What a great tutorial! We all should be grateful that Beau did such a great job, and built the app step by step. I learned a lot from this video. Having the source code on github allowed me to check my mistakes. Thanks again!
hi I have one react redux application in which php files are present for api calls so i am not able to run it on
localhost but it works fine on web server any help will be appreciate
Thanks
works ok however very slow on my machine! would be interested in seeing a video on how to optimize this. would also be interested in seeing how to implement a version where the bounding box of the grid flows from one side to the opposite side once it reaches the edge.
Thanks this is great. Question why do the "Generations" continue to run when the cells stop populating?
@24:15 You could do:
onClick = {() => this.props.selectBox(this.props.row, this.props.col)}
15:12 feel like unnecessary use of map. Simpler solution would be:
gridFull = Array(this.rows).fill(Array(this.cols).fill(false))
why add Buttons affected layout of Grid? don't really understand.
the grid layout still has problem when the window size changed.
I have tried building this along with you and even copied and pasted the play function code and more from the repo and yet, though it appears to work right, if I actually inspect how a seed plays out, I am consistently getting some different results than what I should. A glider does not work for instance, nor a blinker or anything else as it should, implying my play function is wrong, but since it is now your code exactly, I know it isn't. I have spent literally over 20 hours checking every line of code, trying different things, and cannot figure out why it doesn't work or where anything relevant to that functioning is different than yours, simply copying in your code whenever I can, and I consistently get it working the same wrong way every single time. Any ideas for why this could be happening?
This is an awesome tutorial, thank you so much! For some reason, when I toggle the boxes and then press play, my toggled boxes immediately disappear. Seems to not be applying my toggled boxes to the state or something. I checked my code against the repo and it's identical, I wonder why the difference in outcome. I will spend some time trying to figure that out…
Thanks again though, this video is a really great, fun, detailed, and thorough walkthrough!!!
I'm getting an infinite loop when I try to run this on CodePen:
class Box extends React.Component {
selectBox = () => {
this.props.selectBox(this.props.row, this.props.col);
}
If I leave it like this, it gives me an error: unexpected token =
If I add a semicolon after the last curly bracket, I get an infinite loop. Any ideas on how to fix that? I'm assuming it's a CodePen issue.
Transforming an array into a string and parsing it back costs a lot! A simpler solution would be: grid.map(array => array.slice())
Thank you for the awesome tutorial Beau! I just finished this challenge on FCC and need to refactor because at larger sizes it goes slow. This tutorial helped with that. I am still learning, but instead of using your helper function to create a copy of the nested array, couldn't you just use the native callback provided by the setState() function? For the selectBox() function It looks like this:
selectBox = (row, col) =>{
this.setState((previousState)=>{
let {gridFull} = previousState;
gridFull[row][col] = !gridFull[row][col]
return {gridFull: gridFull }
});
}
In the code line 191 (it's line 107 when first pasted at 36:10) first condition is 'if (i < this.rows – 1 && this.cols – 1)'. Shouldn't there be 'if (i < this.rows – 1 && j < this.cols – 1)' instead?
Clear and nice video thank u
I programmed the algorithm for play myself, and found the boxes would just disappear slowly and then flash on and off in different places. Then I literally commented out my code, and pasted yours, and it STILL did the same thing, looking nothing like the expanding life that yours shows. What gives?
Excellent tutorial. Thank you!
Would have been nice to explain the algorithm more at 37 mins.
Set speed: 1.25x
Thanks for tutorial!
nice tutorial, ultimately annoying whiny voice
i am getting this error:
TypeError: Cannot read property '0' of undefined
Grid.render
C:/Users/PrAbEsH/Desktop/Traversy/beauReact/gamoflife/src/index.js:30
27 | for (var j = 0; j < this.props.cols; j++) {
28 | let boxId = i + "_" + j;
29 |
> 30 | boxClass = this.props.gridFull[i][j] ? "box on" : "box off";
31 | rowsArr.push(
32 | <Box
33 | boxClass={boxClass}
HELP!!!
( ͡° ͜ʖ ͡°)