Let's Code

Posted on

ReactJS Tic-Tac-Toe (💥Passed Job Interview💥)

Hello Everyone! I wanted to share my success on my previous job interview where I was asked to code a tic-tac-toe game in ReactJS and was able to pull it off landing a job offer. 🎉🥳 This is not the first time I was asked to code this game 🎮 but on different interviews as well. Other interviews was in plain vanilla JS.

My recommended approach to solving this challenge is list 📙 the steps of how would you solve it (just like the video I have below) then code those step one by one. You will get credit 💯 even if you don't finish the game. In case you do not finish the challenge, just talk about how would you code the rest of the steps and you will most likely still be successful in the interview.

Here is how I did it. I created two 2️⃣ components - Square and Board Component and a Helper Function to calculate the winner.

Square Component

``````function Square({ onClick, value }) {
return (
<button className="square" onClick={onClick}>
{value}
</button>
);
}
``````

Board Component

``````function Board () {
const [squares, setSquares] = React.useState(Array(9).fill(null))
const [isX, setIsX] = React.useState(true);

const handleClick = (i) => {
if (calculateWinner(squares) || squares[i]) {
return
}

squares[i] = isX ? 'X' : 'O'
setSquares(squares)
setIsX(!isX)
}

const winner = calculateWinner(squares)
let status

if (winner) {
status = `Winner: \${winner}`;
} else {
status = 'Next player: ' + (isX ? 'X' : 'O');
}

const handleRestart = () => {
setIsX(true)
setSquares(Array(9).fill(null))
}

const renderSquare = (i) => {
return <Square value={squares[i]} onClick={() => handleClick(i)} />
}

return (
<div className="board">
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
<div className="status">{status}</div>
<button className="restart" onClick={handleRestart}>Restart Game!</button>
</div>
)
}
``````

Helper Function To Calculate A Winner

``````function calculateWinner(squares) {
const winningPatterns = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]

for (let i = 0; i < winningPatterns.length; i++) {
const [a, b, c] = winningPatterns[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
``````

Below are some codepen links if you want to play around my solution. Also, a link to the exercise to avoid the setup and if you want to try it yourself.

Final Thoughts:
This interview challenge is tough but can be fun. It would refresh your knowledge with ReactJS concepts and fundamentals. It might even help you land your dream job if you get asked to do this challenge so it is a win-win and may be valuable to you.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Listing a collection of my previous ReactJS post if you need some help with a potential interview with this library.

Common React Interview Questions

10 ReactJS Coding Challenge (💥Coding Interview Prep💥)

(I created a 7-minutes video that is fast and painless to explain details step-by-step as I see other tutorials that is 20 minutes to 1 hour long which can be greatly condensed into something way smaller)

Thanks for the exercise!
It helped me to prepare for an upcoming interview.
I made this version with some variations ;)
codepen.io/jusrecondo/pen/GRBxPJv

Let's Code

glad to hear that my post helped out in some way. Good luck on your upcoming interview.

Amn3s1a2018

If I was the interviewer, I would ask you about the asynchronous setSquares function. Also would be nice to refactor isX and isThereWinner to derived state

Let's Code

nice follow up questions. thanks for sharing.

Let's Code • Edited on

Where you asked to do the same challenge on your previous job interviews?

Should this coding challenge even be used when screening out candidates?

Veronica Valenzuela

This was really good practice for me, do you have any other react interview coding challenges like this one? What level would you say this question would be good for?

Let's Code • Edited on

Hi Veronica,

here is a good one that I get a lot of great feedback - dev.to/frontendengineer/10-reactjs...

I would say this is a good question for senior devs/engineers

Mopano

Great , thanks for Information. Have you got group in Telegram or ... that we can join and ask our Problems ? If Not, we can do this together😃

SF Esports

How the previous choices are being stored ?

Let's Code

on the handleClick - `setSquares(squares)`

Let's Get Hacking

Join the DEV x Linode Hackathon 2022 and use your ingenuity and creativity to build using Linode.

Join the Hackathon <-