DEV Community

Let's Code
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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

Tic-Tac-Toe Codepen Solution
Tic-Tac-Toe Codepen Exercise

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

Advance 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)

Top comments (10)

Collapse
 
jusrecondo profile image
jusrecondo • Edited

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

Collapse
 
frontendengineer profile image
Let's Code

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

Collapse
 
amn3s1a2018 profile image
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

Collapse
 
frontendengineer profile image
Let's Code

nice follow up questions. thanks for sharing.

Collapse
 
frontendengineer profile image
Let's Code • Edited

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

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

Collapse
 
veronicamarie24 profile image
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?

Collapse
 
frontendengineer profile image
Let's Code • Edited

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

Collapse
 
mopano profile image
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😃

Collapse
 
sf_esports profile image
SF Esports

How the previous choices are being stored ?

Collapse
 
frontendengineer profile image
Let's Code

on the handleClick - setSquares(squares)