Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="errors" style="
  background: #c00;
  color: #fff;
  display: none;
  margin: -20px -20px 20px;
  padding: 20px;
  white-space: pre-wrap;
"></div>
<div id="root"></div>
<script>
window.addEventListener('mousedown', function(e) {
  document.body.classList.add('mouse-navigation');
  document.body.classList.remove('kbd-navigation');
});
window.addEventListener('keydown', function(e) {
  if (e.keyCode === 9) {
    document.body.classList.add('kbd-navigation');
    document.body.classList.remove('mouse-navigation');
  }
});
window.addEventListener('click', function(e) {
  if (e.target.tagName === 'A' && e.target.getAttribute('href') === '#') {
    e.preventDefault();
  }
});
window.onerror = function(message, source, line, col, error) {
  var text = error ? error.stack || error : message + ' (at ' + source + ':' + line + ':' + col + ')';
  errors.textContent += text + '\n';
  errors.style.display = '';
};
console.error = (function(old) {
  return function error() {
    errors.textContent += Array.prototype.slice.call(arguments).join(' ') + '\n';
    errors.style.display = '';
    old.apply(this, arguments);
  }
})(console.error);
</script>
              
            
!

CSS

              
                body {
    font: 14px "Century Gothic", Futura, sans-serif;
    margin: 20px;
  }
  
  ol, ul {
    padding-left: 30px;
  }

  li.active button {
    font-weight: bold;
  } 
  
  .board-row:after {
    clear: both;
    content: "";
    display: table;
  }
  
  .status {
    margin-bottom: 10px;
  }
  
  .square {
    background: #fff;
    border: 1px solid #999;
    float: left;
    font-size: 24px;
    font-weight: bold;
    line-height: 34px;
    height: 34px;
    margin-right: -1px;
    margin-top: -1px;
    padding: 0;
    text-align: center;
    width: 34px;
  }
  
  .square:focus {
    outline: none;
  }
  
  .win {
    background-color: cyan;
  }

  .kbd-navigation .square:focus {
    background: #ddd;
  }
  
  .game {
    display: flex;
    flex-direction: row;
  }
  
  .game-info {
    margin-left: 20px;
  }
  
  .toggle {
    display: flex;
  }
  .toggle input {
    display: none;
  }
  .toggle label{
    /*display: block;
    float: left;*/
    cursor: pointer;
    width: auto;
    margin: 0;
    padding: 0.25rem;
    background: #bdc3c7;
    color: #869198;
    font-size: 0.75rem;
    text-align: center;
    line-height: 1;
    transition: .2s;
  }
  .toggle label:first-of-type{
    border-radius: 3px 0 0 3px;
  }
  .toggle label:last-of-type{
    border-radius: 0 3px 3px 0;
  }
  .toggle input[type="radio"]:checked + .switch-on {
    background-color: #a1b91d;
    color: #fff;
  }
  .toggle input[type="radio"]:checked + .switch-off {
    background-color: #e67168;
    color: #fff;
  }
              
            
!

JS

              
                function Square(props) {
    return (
        <button className={props.className} onClick={props.onClick}>
            {props.value}
        </button>
    );
}
  
class Board extends React.Component {
    renderSquare(i) {
        let className = 'square';
        if (
            this.props.line !== null
            && this.props.line.indexOf(i) !== -1
        ) {
            className += ' win';
        }
        return (
        <Square
        className={className}
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
        key={i}
        />
        );
    }

    createBoardHtml() {
        let square, div = [];
        let num = 0;
        for (let i = 0; i < 3; i++) {
            square = [];
            for (let j = 0; j < 3; j++) {
                num = 3 * i + j;
                square.push(this.renderSquare(num));
            }
            div.push(<div className="board-row" key={i}>{square}</div>);
        }
        return div;
    }
  
    render() {
        return (
        <div>
            {this.createBoardHtml()}
        </div>
        );
    }
}

class Toggle extends React.Component {
    render() {
        return (
            <div className="toggle">
                <span>Hisotry order:&nbsp;</span>
                <input type="radio" name="order" id="asc" value="asc" checked={this.props.order === 'asc'}
                    onChange={() => this.props.onChange()}/>
                <label htmlFor="asc" className="switch-on">ASC</label>
                <input type="radio" name="order" id="desc" value="desc" checked={this.props.order === 'desc'}
                    onChange={() => this.props.onChange()}/>
                <label htmlFor="desc" className="switch-off">DESC</label>
            </div>
        )
    }
}

class Game extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            history: [{
                squares: Array(9).fill(null)
            }],
            stepNumber: 0,
            xIsNext: true,
            clickPosition: {
                col: null,
                row: null
            },
            order: 'asc',
        };
    }

    handleClick(i) {
        const history = this.state.history.slice(0, this.state.stepNumber + 1);
        const current = history[history.length - 1];
        const squares = current.squares.slice();
        const position = getPosition(i);
        if (calculateWinner(squares).winner || squares[i]) {
            return;
        }
        squares[i] = this.state.xIsNext ? 'X' : 'O';
        this.setState({
            history: history.concat([{
                squares: squares
            }]),
            stepNumber: history.length,
            xIsNext: !this.state.xIsNext,
            clickPosition: position
        });
    }

    handleChange() {
        const order = this.state.order === 'asc' ? 'desc' : 'asc';
        this.setState({
            order: order
        });
    }

    jumpTo(step) {
        this.setState({
            stepNumber: step,
            xIsNext: (step % 2) === 0,
        });
    }

    render() {
        const history = this.state.history;
        const current = history[this.state.stepNumber];
        const win = calculateWinner(current.squares);
        const winner = win.winner;
        const line = win.line;

        let moves = history.map((step, move) => { // step: value of array(history) , move: index of array(history)
            const desc = move ?
                'Go to move #' + move :
                'Go to game start';
            const className = move === this.state.stepNumber ? 'active' : '' ;
            return (
                <li key={move} className={className}>
                    <button onClick={() => this.jumpTo(move)}>{desc}</button>
                </li>
            );
        });

        if (this.state.order === 'desc') {
            moves = moves.reverse();
        }

        let status ;
        if (winner) {
            status = 'Winner: ' + winner;
        } else {
            if (this.state.stepNumber == 9)
                status = 'Result:draw';
            else 
                status = 'Next player:' + (this.state.xIsNext ? 'X' : 'O');
        }

        return (
        <div className="game">
            <div className="game-board">
            <Board
                line={line}
                squares={current.squares}
                onClick={(i) => this.handleClick(i)}
            />
            </div>
            <div className="game-info">
            <div>col:{this.state.clickPosition.col}, row:{this.state.clickPosition.row}</div>
            <div>{status}</div>
            <Toggle
                order={this.state.order}
                onChange={() => this.handleChange()}
            />
            <ol>{moves}</ol>
            </div>
        </div>
        );
    }
}
  
// ========================================

ReactDOM.render(
<Game />,
document.getElementById('root')
);

function calculateWinner(squares) {
    const lines = [
      [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 < lines.length; i++) {
      const [a, b, c] = lines[i];
      if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
        return {
            'winner': squares[a],
            'line': lines[i]    // winner's line
        };
      }
    }
    return {
        'winner': null,
        'line': null
    };
}

function getPosition(index) {
    let pos = [];
    for (let row = 1; row <= 3; row++) {
        for (let col = 1; col <= 3; col++) {
            pos.push({
                row: row,
                col: col
            });
        }
    }
    return pos[index];
}
              
            
!
999px

Console