Skip to content

Latest commit

 

History

History
372 lines (254 loc) · 6.26 KB

File metadata and controls

372 lines (254 loc) · 6.26 KB

web team

<ReactWorkshop />


JavaScript

a quick crash course


Objects and Functions

  • Objects in JavaScript specified with {}
  • Objects describe key-value mappings with key: value,
  • Keys can map to any kind of value
    • Number, String, Object, Function, Array, etc.
var car = {
  gas: 30,
  drive: function() {
    console.log("Beep!");
  },
  name: "Ethan's Car",
}

Objects and Functions, continued

  • The this keyword describes the callee of a function - the object that invokes the function
var car = {
  gas: 30,
  drive: function(miles) {
    this.gas = this.gas - miles / this.mpg;
  },
  mpg: 16,
  name: "Ethan's Car",
}

Closures

  • JavaScript specifies functional scope
function a() {
  var x = 3;
}

console.log(x); // x is undefined

Revisiting this

  • this is the caller of a function, always
var x = {
  y: function() {
    console.log(this);
  },
  z: 10
};
x.y();
  • What does x.y() output?
> { y: [Function], z: 10 }

Revisiting this, continued

  • How about this one?
var x = {
  y: function() {
    console.log(this);
  },
  z: 10
};
var huh = x.y;
huh();
> [Window global]

ES6 Primer

  • JavaScript is growing, features are being added to the language

  • Arrow Functions

var sum = (a, b) => {
  return a + b;
}

// or more succinctly:
var sum = (a, b) => a + b;

ES6 Classes

class Car {
  constructor(name) {
    this.name = name;
    this.gas = 30;
    this.mpg = 15;
  }

  drive(miles) {
    this.gas -= this.mpg / miles;
  }
}

More ES6 features (what is ... ???)

  • Object Destructuring
var x = { y: 3, z: "hello" };
var { y, z } = x;
  • Spread Operators
var arr = [1, 2, 3, 4];
var sum = (...args) => args.reduce((v, c) => v + c);

Even more ES6 Features

  • Template strings
var sayHappyBirthday = (name) => `Happy birthday, ${name}!`;
  • let and const - block scope
if (true) {
  let x = 5;
}
console.log(x); // undefined

A brief history

From AJAX to $ to React


What is AJAX?

  • Asynchronous JavaScript and XML
  • Used to request resources over HTTP, without a page reload
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
  if (request.readyState === XMLHttpRequest.DONE) {
    console.log(httpRequest.responseText);
  }
};
request.open('GET', 'https://1crb6kfpove4.runkit.sh/status', true);
request.send();

AJAX and the DOM

  • An idea: send an AJAX request and place it into our page
var status = document.querySelector('#status');
request.onreadystatechange = function() {
  if (request.readyState === XMLHttpRequest.DONE) {
    status.innerHTML = request.responseText;
  }
};

AJAX and DOM string templates

  • A better idea: send an AJAX request and generate elements that get placed into our page
function generateStatusBar(status) {
  return "\
    <div class='status'>\
      <h1>" + status + "</h1>\
    </div>\
  ";
}

$("body").append(
  $(generateStatusBar(request.responseText))
);
  • $ is jQuery, a tool for making selecting DOM nodes and manipulating them way easier

This gets messy!

  • Managing a bunch of different generateAnotherComponent(withParam1, withParam2) across different files (or one huge one), for every single dynamic component you need, is bad
  • We need a way to create stateful components in an HTML page and render their data dynamically

Enter React

  • A result of the Facebook ads team - creating complex interfaces with lots of data entry is hard!
  • A composable view library to manage self-contained components that consume a lot of data

Thinking in React


Codealong!


Anatomy of rendering a JSX element

  <MyComponent
    aProp="string value for a prop"
    bProp={3} /* number value for a prop */
    cProp={(a, b) => a + b} /* function value for a prop */
    dProp={{ textAlign: 'left' }} /* object value for a prop */
  >
    {children}
  </MyComponent>

Anatomy of a component

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      /* Set a first step for state */
    };
  }

  componentDidMount() {
    /* Do some setup */
  }

  render() {
    /* Return JSX or value */
    return (<h1>{this.props.aProp}</h1>);
  }
}

Key lifecycle methods

  • constructor(): Initialize state and setup the component (before mounting)
  • componentDidMount(): Perform asynchronous actions after the component has mounted
  • render: Return one JSX element (possibly with children) that you want to display
    • render should be a pure function of state and props

State vs. Props

  • props are passed down from a parent and can cause a component to update
  • state is modified within a component instance and can cause a component to update
  • state only modified with this.setState

Exercise

Build a simple React app in CodePen that renders the weather in a user-specified city!