Class Components

So far the way we have been writing components has been functional like so.

const Hello = (props) => (  
  <div>
    <h2>Hello {props.name}</h2>
  </div>
)

You can also use an ES6 class to define a component. Instead of returning the JSX the class component has a render method that returns that component. Props are also no longer passed as an argument, it is now a property of the component that is available through "this.props".

class Hello extends React.Component {  
  render() {
    return (
      <div>
        <h2>Hello {this.props.name}</h2>
      </div>
    )
  }
}

It also introduces a new concept of state. State is changing data stored in a component.

class Counter extends React.Component {  
  constructor() {
    super();
    this.state = {counter: 0}
    this.up = this.up.bind(this);
    this.down = this.down.bind(this);
  }
  up() {
    this.setState((prevState) => ({counter: prevState.counter + 1}));
  }
  down() {
    this.setState((prevState) => ({counter: prevState.counter - 1 }));
  }
  render() {
    return (
      <div>
        <h2>{this.state.counter}</h2>
        <button onClick={this.up}>Up</button>
        <button onClick={this.down}>Down</button>
      </div>
    )
  }
}

Learn more about state here.