ReactJS Tic-Tac-Toe (💥Passed Job Interview💥)
Tags: react, javascript, career, showdev
Published: 2022-02-19 16:53:51

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**
```jsx
function Square({ onClick, value }) {
  return (
    <button className="square" onClick={onClick}>
      {value}
    </button>
  );
}
```

**Board Component**
```jsx
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**
```js
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.

[Tic-Tac-Toe Codepen Solution](https://codepen.io/angelo_jin/pen/GROEdMK)
[Tic-Tac-Toe Codepen Exercise](https://codepen.io/angelo_jin/pen/OJOmXWG)

**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](https://dev.to/frontendengineer/common-react-interview-questions-50gm)

[Advance React Interview Questions](https://dev.to/frontendengineer/react-interview-questions-part-2-mid-senior-level-cal)

[10 ReactJS Coding Challenge (💥Coding Interview Prep💥)](https://dev.to/frontendengineer/10-reactjs-coding-exercises-with-codepen-exercise-and-solution--22k7)

{% youtube w8V--ZBzh7w %} 
(*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*)