Build a Tic Tac Toe App with TypeScript, React and Mocha

Home Dev Build a Tic Tac Toe App with TypeScript, React and Mocha

Learn how to compose a tic-tac-toe app with React and TypeScript components.

Go to the profile of Josh Kuttler

A simple Tic-Tac-Toe game built with modularity in mind and shared on Bit. After sharing, my game’s components can be tweaked and tested on Bit’s live PlayGround. Go to my components collection on Bit to test or consume the entire game or just some of its components, using NPM, Yarn or Bit.

When building a game like Tic-Tac-Toe “with modularity in mind”, it’s hard to think of a reason for the UI components to be reused ever again, so I kept my focus primarily on the game’s utility functions.

I chose TypeScript as my coding language of choice — compiled by Bit’s TypeScript compiler and used Mocha for testing.

To install components from my project, first configure bit.dev as a scoped registry (copy and paste to your terminal) — this is done only once! later uses of bit do not require you to configure again.

npm config set '@bit:registry' https://node.bit.dev

and then install the component using Yarn or NPM:

npm i @bit/joshk.tic-tac-toe-game.game
yarn add @bit/joshk.tic-tac-toe-game.game

Game Component

The ‘game’ component is my app’s main component — composed using one component from ‘Board’ and two components from ‘Prime React’.

I used the button and the input-text for the configuration screen — test and see the code here.

Install PrimeReact components in your project:

yarn add @bit/primefaces.primereact.inputtext
yarn add @bit/primefaces.primereact.button

After setting the parameters, you can click ‘Play’ and… Play!

Board Component

The board component creates a dynamic table by props, manage player turn and check for the winner. Test and see the code here.

Square Component

The square component is a simple cell that receives value with optional color and sends an event to the board component when the value changes. Test and see the code here.

Empty cell function

‘Empty cell function’ Is a helper function to winner-calc function that checks if there are any empty cells in the game’s table.

Bit lets you see the docs for the component and the results of the tests:

The code of the function:

Winner Calculation

Winner calculation is a function that checks for the winner in horizontal, vertical and diagonal cases.

Bit let you see the docs for the component and the results of the tests:

The code for the function:

The project is available in my bit collection and in my GitHub repository:

Feel free to comment below and follow me on Twitter 😃

Learn More

Leave a Reply

Your email address will not be published.