Let's Learn React

Part 2

nb: I want to be able to write <<parts_macro "lets_learn_react_" "2" "7">> and have it insert a nav-block for navigating amongst the parts of a tutorial. Likewise, probably a next/previous macro to turn the pages at the bottom of the page.

OK - the tutorial.

Components - are composed just like HTML elements.

To people who've been around this way of mixing together HTML syntax, Javascript and CSS is very unusual and possibly feels like the wrong thing to do. An important principle has been a separation of concerns.

But this is 'canonical React'.

We're given this starter code

class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {/* TODO */}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square />;
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

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

We can see that there are three different components.

The Square component returns a Button, the Board component returns a Div containing three Divs, each containing 3 Squares.

The Game component returns a Div with 2 Divs in it, the first has class 'game-board' and contains a single instance of Board.

The second one contains a 'status' div and an ordered list, both currently empty.

Note that HTML elements start with a lower-case letter and React elements start with a Capital Letter and are otherwise interchangeable.

Note that we have to use the attribut "className" instead of "class" - why? (I think because class is reserved and this is not official usage?)

When trying to understand this, don't be too worried about how it's actually working - remember that React is sitting behind all this running like a black-box and we don't know how it works.

Next, we're going to pass props into components.

    return <Square value={i} />;