React in 30 seconds-ish

React is a component framework, for creating small bits of reusable, configurable markup.

import MyContentComponent from './my-content-component';

React uses a special syntax called JSX. It looks like HTML in your JavaScript:

<div>
  <p>
    {['This', 'is', 'normal', 'javascript', 'stuff.'].join(' ')}
  </p>
</div>

Simple components can be written as functions that return JSX.

// Define a component
const MyContentComponent = () => <div>Content!</div>


// Use it somewhere
<MyContentComponent />

Components can be configured by passing data to them through props.

// Define
const MyContentComponent = (props) => (
  <div>
    <h1>{props.header}</h1>
  </div>
);

// Use
<MyContentComponent header="Hello world" />

Props are data that get passed to components, but components can also have their own internal data. To use it we make a class component and give it a state property.

class MyContentComponent extends React.Component {
  state = { randomDay: 'Wednesday' }

  render() {
    return (
      <div>
        <h1>Hello World, it is {this.state.randomDay}!</h1>
      </div>
    );
  }
}

You can update internal state using setState.

import randomChoice from 'some-lib';

class MyContentComponent extends React.Component {
  state = { randomDay: 'Wednesday' }

  getRandomDay = () => {
    const days = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'FRIDAY!!🎉'
    ];

    this.setState({
      randomDay: randomChoice(days)
    });
  }

  render() {
    return (
      <div>
        <h1>Hello World, it is {this.state.randomDay}!</h1>
        <button
          onClick={this.getRandomDay}
        >Rando</button>
      </div>
    );
  }
}

Class components also have some special methods that run at different points during the components lifecycle. We'll be using componentDidMount and componentDidUpdate.

class MyComponent extends React.Component {
  // Runs right after the render function renders DOM
  componentDidMount() {
    console.log('Hello world!');

    document.getElementById('my-div');
  }

  // Runs anytime component gets new props or sets new state
  componentDidUpdate() {
    console.log('Got new state or props!', this.props, this.state);
  }

  // Runs right before component is removed from DOM
  componentWillUnmount() {
    console.log('Out, out, brief candle! 💀');
  }

  render() {
    return (
      <div id='my-div'/>
    )
  }
}

🏁 Fin.