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

frontendengineer

Let's Code

Posted on February 19, 2022

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)

💖 💪 🙅 🚩
frontendengineer
Let's Code

Posted on February 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related