React for Beginners

For core concepts see 1 - Web Dev/React Core Concepts

A refresher for intermediate React engineers.

Props

What are props?

class App extends React.Component {
  render() {
    return (
      <div className="catch-of-the-day">
        <div className="menu">
        {/* tagline is the prop */}
          <Header tagline="Fresh Seafood Market"/>
        </div>
        <Order />
        <Inventory />
      </div>
    )
  }
}
const Header = props => (
  <header className="top">
    <h1>
      Catch
      <span className="ofThe">
        <span className="of">Of</span>
        <span className="the">The</span>
      </span>
      Day
    </h1>
    <h3 className="tagline">
     {/* here we are passing the data/props into the Header component */}
      <span>{props.tagline}</span>
    </h3>
  </header>
);

Stateless Functional Components

// Presentational component
const Header = props => (
  <header className="top">
    <h1>
      Catch
      <span className="ofThe">
        <span className="of">Of</span>
        <span className="the">The</span>
      </span>
      Day
    </h1>
    <h3 className="tagline">
     {/* functions have no `this` */}
      <span>{props.tagline}</span>
    </h3>
  </header>
);

Helper functions

export function rando(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

import { rando } from '../helpers.js

import React from 'react'

Events and Refs

handleSubmit(e) {
  e.preventDefault();
  console.log('Going to store')
}
<button onClick={this.handleSubmit}>Click Me</button>
class StorePicker extends React.Component {
  myInput = React.createRef();

  handleSubmit(e) {
   e.preventDefault();
   console.log('Going to store')
  }
  render(){
    return (
      <form className="some-class" onSubmit={this.handleSubmit}>
        <h2>Please enter a store</h2>
        <input
          type="text"
          ref={this.myInput}
          required
          placeholder="Store Name"
          defaultValue={rando()}
        >
      </form>
    )
  }
}
class StorePicker extends React.Component {
  constructor() {
    super();
    {/* will bind `this` to this exact component */}
    this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
   e.preventDefault();
   console.log('Going to store')
  }
  render(){
    return (
      <form className="some-class" onSubmit={this.handleSubmit}>
        <h2>Please enter a store</h2>
        <input
          type="text"
          ref={this.myInput}
          required
          placeholder="Store Name"
          defaultValue={rando()}
        >
      </form>
    )
  }
}

Handling Events

State

https://news.ycombinator.com/item?id=31088065