Reactshop

Introduction to React

Workshop by Piotr Staniów

Reactshop - Agenda

  • ES6 recap
  • Introduction to JSX
  • Introduction to React
  • Reactshop - live coding session

ECMAScript 6

ECMA-262 is the de facto standard for JavaScript language implementation
We'll review some features in versions 2015+

Scope of variables

Lexically bound variables

function(x) {
  var a = 5;
  if (x) {
    var b = 3;
  }
  // Both a and b are declared here
}

Block-scoped variables

function(x) {
  let a = 5;
  const b = { p: 3 }; // Constant reference
  if (x) {
    let c = 17;
    const d = 0;
  }
  // Only a and b are declared here
  b.p = 7; // VALID
  b = { q: 3 }; // TypeError
}

Destructuring

Shorthand notation for extracting properties

const obj = {
  a: 1,
  b: 2,
}
const arr = [5, 4, 3];

const { a, b } = obj; // const a = obj.a; const b = obj.b;
let [ p, q, r ] = arr; // const p = arr[0]; ...
function test({ a, b }, [p, q, r]) {
  console.log(a, b, p, q, r);  
}
test(obj, arr); // Prints 1 2 5 4 3

Arrow Function (Lambda)

function ex1(a, b) {
  console.log(a, b);
  return a + b;
}
const ex2 = (a, b) => {
  console.log(a, b);
  return a + b;
}
const ex3 = (a, b) => a + b;
const ex4 = a => 5 * a;

Arrow function does not bind `this` - it's used as variables from closures

Classes

ES6 introduces new way of declaring classes

function Klass(a, b) {
  this.member = 5;
  this.member2 = 17;
}
Klass.prototype = new BaseClass();
Klass.prototype.method = function() { 
  return this.member;
}
var k = new Klass();
class Klass extends BaseClass {
  member2 = 17; // Alternative
  constructor() {
    this.member = 5;
  }
  method() {
    return this.member;
  }
}
const k = new Klass;

Other features

ES6 and newer introduce also other features, including:

  • Default function parameters (a = 3) => a
  • Rest parameter (a, ...rest) => a
  • Spread operator { ...shallowCopy, a: 3 }
  • Template literals `Hello ${name}`
  • Property shorthand: { a: a } becomes { a }
  • for-of loops
  • Generator function function*() { yield 5; }
  • Promises Promise.resolve(5).then(k => 3).finally()
  • async/await
  • Object.entries({ a: 5}) and Object.values({ a: 5})

JSX Harmony

  • It's an extension of JavaScript
  • Allows embedding XML in JavaScript
  • It's not required to use React but it's convenient

JSX Harmony

JSX allows using XML as an expression

const value = 5 + 4;
const element = <h1>Hello world</h1>;

JSX Harmony

JSX is transpiled* to React functions calls

const element = <div className="header">Hello world!</div>;
is transpiled to:
const element = React.createElement({
  'div',
  { className: 'header' },
  'Hello world!'
});
and the call returns:
const element = {
  type: 'div',
  props: {
    className: 'header',
    children: 'Hello world!',
  },
};
*mix of words: translate & compile

JSX Harmony

You can embed JavaScript expressions in JSX too

{ Simply put them in brackets }
const name = 'Thomas';
const element = <div className="header">Hello {name}!</div>;
You can go crazy with it too...
const element = (
  <ul>
    { ['A', 'B', 'C'].map(el => <li key={el}>{el}</li>) }
  </ul>
);

JSX Harmony

That's it for JSX!

React

The main purpose of each web framework is to extend HTML with custom <elements> and attributes

...and to encapsulate some logic tied to them.

React DOM

React is used to build Single Page Applications (SPA) and hence it has a single root component.

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  

Hello world

, document.querySelector('div#root'), );

Components

There are two ways of writing components:

Class components

import React from 'react';

export class App extends React.Component {
  render() {
    return 

Welcome, {this.props.name}!

; } }

Functional (stateless) components

import React from 'react';

export function Welcome(props) {
  return 

Welcome, {props.name}!

; }

Composing components

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
export class App extends React.Component {
  render() {
    return (
      <div>
        <Welcome name="Sara" />
        <Welcome name="Cahal" />
        <Welcome name="Edite" />
      </div>
    );
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Extracting Components

export const Comment = (props) => (
  <div className="comment">
    <div className="user-info">
      <img className="avatar"
        src={props.author.avatarUrl}
        alt={props.author.name}
      />
      <div className="user-name">
        {props.author.name}
      </div>
    </div>
    <div className="comment-text"> {props.text} </div>
    <div className="comment-date"> {formatDate(props.date)}</div>
  </div>
);

Avatar and user info don't belong here

Extracting Components

function Avatar(props) {
   return (
     <img className="Avatar"
       src={props.user.avatarUrl}
       alt={props.user.name}
     />
   );
 }
function UserInfo(props) {
  return (
    <div className="UserInfo">
      <Avatar user={props.user} />
      <div className="UserInfo-name">
        {props.user.name}
      </div>
    </div>
  );
}

Let's see it in action...

Extracting Components

 function Comment(props) {
   return (
     <div className="Comment">
       <div className="UserInfo">
         <Avatar user={props.author} />
         <div className="UserInfo-name">
           {props.author.name}
         </div>
       </div>
       <div className="Comment-text">{props.text}</div>
       <div className="Comment-date">{formatDate(props.date)}</div>
     </div>
   );
 }

Extracting Components

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Fancy Input

Component state

class FancyInput extends React.Component {
  constructor(props) {
    super(props); // Call to base class is required
    this.state = { value: props.initialValue };
  }

  render() {
    const { value } = this.state;
    return <input type="text" value={value} />;
  }
}
Usage:
<FancyInput initialValue="Type here..." />

Event handlers

class FancyInput extends React.Component {
  constructor(props) {
    super(props); // Call to base class is required
    this.state = { value: props.initialValue };
  }

  handleChange(event) {
    console.log('Input value has changed!', event.target.value);
  }

  render() {
    const { value } = this.state;
    return <input type="text" value={value} onChange={this.handleChange} />;
  }
}

Updating state

class FancyInput extends React.Component {
  constructor(props) {
    super(props); // Call to base class is required
    this.state = { value: props.initialValue, other: 5 };
  }

  handleChange(event) {
    this.setState({ value: event.target.value })
  }

  render() {
    const { value } = this.state;
    return <input type="text" value={value} onChange={this.handleChange.bind(this)} />;
  }
}

Styles

class FancyInput extends React.Component {
  constructor(props) {
    super(props); // Call to base class is required
    this.state = { value: props.initialValue, other: 5 };
  }

  handleChange(event) {
    this.setState({ value: event.target.value })
  }

  render() {
    const { value } = this.state;
    const style = { border: `3px solid ${value === 'zielony' ? 'green' : 'red'}` };
    return <input type="text" style={style} value={value} onChange={this.handleChange.bind(this)} />;
  }
}

Reactshop

An online application for shopping made with React

Step 1 - Warm up

Our first goal is to create a Homepage that a user will see when visiting our shop.
It will display the page layout and categories available for shopping.

  • Look around in App.js. It is a right place to render a grid of categories.
  • Add div container and some div elements inside it.
    You can use category-grid and category-item classes that already have some CSS styles assigned. Add a few categories.