Skip to content

Instantly share code, notes, and snippets.

@tiero
Last active October 15, 2018 09:52
Show Gist options
  • Save tiero/9dcde3d5d3682745117c5ad54663a052 to your computer and use it in GitHub Desktop.
Save tiero/9dcde3d5d3682745117c5ad54663a052 to your computer and use it in GitHub Desktop.

Introduction to React.js Development

Table of Contents

  1. Rationale
  2. HTTP
  3. Browser
  4. Javascript
  5. JSX
  6. Lifecycle
  7. Props
  8. State
  9. Enviroment
  10. Exercices

Rationale

Disclaimer: Don't be a commodity developer. Period.

Why React?

  • Declarative

React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Declarative views make your code more predictable and easier to debug.

  • Component based

Build encapsulated components that manage their own state, then compose them to make complex UIs.

Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.

  • Learn Once, Write Anywhere

You can develop new features in React without rewriting existing code. React can also render on the server using Node and power mobile apps using React Native.

HTTP

http main usecase

Browser

browser explained

Javascript

js hell

A re-introduction to JavaScript

  • Callbacks, Promise or async/await
  • ES6/ES7 (arrow functions, classes, spread operator, let, and const)
  • Babel
  • Webpack

JSX

Component

React components are small, reusable pieces of code that return a React element to be rendered to the page. The simplest version of React component is a plain JavaScript function that returns a React element:

import React from 'react'

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Components can also be ES6 classes:

import React from 'react'

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
}

Lifecycle

Lifecycle methods are custom functionality that gets executed during the different phases of a component. There are methods available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

componentWillUnmount()

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

Props

props are inputs to a React component. They are data passed down from a parent component to a child component.

Remember that props are readonly. They should not be modified in any way:

// Wrong!
props.number = 42;

If you need to modify some value in response to user input or a network response, use state instead.

State

A component needs state when some data associated with it changes over time. For example, a Checkbox component might need isChecked in its state.

Enviroment

  • Node > 8
  • npm > 6

You can use nvm (macOS/Linux) or nvm-windows to easily switch Node versions between different projects.

Create-react-app

Create React apps with no build configuration using this module create-react-app

Choose a name for your project like my-app-name

npm init react-app my-app-name

Development

Being in the my-app-name folder, run the app for development

npm start

Build for production

npm run build

Exercises

I know you are lazy, here's the code jsfiddle

Let's create a simple todo-list app.

To be very naive we are going to need a state composed by a list of todos and the current todo being entered.

In your main app component write some like this

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      currentTodo: '',
      todos: []
    };
  }

  render() {
    return (
      <div>
        <form>
          <input value={this.state.currentTodo}  />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

We need a function that takes care of updating the state once the user start typing. We call it onChangeText

constructor() {
...
//Don't forget to bind methods to this context
this.onChangeText = this.onChangeText.bind(this);
}

onChangeText(event) {
  this.setState({ currentTodo: event.target.value });
}

render() {...}

We need to bind this function to the onChange prop of the input form

<input value={this.state.currentTodo} onChange={this.onChangeText} />

Now we want to update the list of todos once the user enter submit

We add a function onSubmitText like this

  constructor(){
  ...
  this.onSubmitText = this.onSubmitText.bind(this);
  }
  
  onSubmitText(event) {
    //The preventDefault() method stops the default action of an element from happening.
    event.preventDefault()
    this.setState({
      currentTodo: '', //We clean the input text
      todos: [...this.state.todos, this.state.currentTodo]
    });
  }
  
  ...
  
  render() {
    <form onSubmit={this.onSubmitText}>
    ...
  }

Then we need to show a list of todos, we use an <ul> component along with Array.map

render() {
    return (
      <div>
        <form onSubmit={this.onSubmitText}>
        ...
        </form>
        <ul>
        {
          this.state.todos.map((todo, index) => <li key={index}>{todo}</li>)
        }
        </ul>
        
      </div>
    );
}

Try it out!

  • index.html
<div id="app"></div>
  • App.js
class App extends React.Component {
  constructor() {
  	super();
    this.state = {
    	currentTodo: '',
      todos: []
    };
    
    this.onChangeText = this.onChangeText.bind(this);
    this.onSubmitText = this.onSubmitText.bind(this);
  }
  
  onChangeText(event) {
  	this.setState({ currentTodo: event.target.value });
	}
  
  onSubmitText(event) {
    //The preventDefault() method stops the default action of an element from happening.
    event.preventDefault()
    this.setState({
      currentTodo: '', //We clean the input text
      todos: [...this.state.todos, this.state.currentTodo]
    });
  }
  
  render() {
    return (
      <div>
        <form onSubmit={this.onSubmitText}>
          <input value={this.state.currentTodo} onChange={this.onChangeText} />
          <button>Submit</button>
        </form>
        <ul>
        {
          this.state.todos.map((todo, index) => <li key={index}>{todo}</li>)
        }
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.querySelector("#app"))

Do you want more exercices? Go grab them.

  1. Increment and Decrease number
  2. Simple API example
  3. Four ways to style react components

BitDealer.io

Frontend demo

API Endpoint

BUY

Insert a purchase order

METHOD

POST  

ENDPOINT

/order/buy

BODY (application/json)

{
	"location": {
		"lat": 53.325131, 
		"lon": -6.254066
	},
	"amountEur": 200,
	"telegramUser": "@tiero",
	"ttl": "1538611240"
}

Get all purchase orders

METHOD

GET  

ENDPOINT

/order/buy?location={"lat":53.272408,"lon":-6.14699}

SELL

Insert a sell order

METHOD

POST  

ENDPOINT

/order/sell

BODY (application/json)

{
	"location": {
		"lat": 53.325131, 
		"lon": -6.254066
	},
  "seller": {
		"signature": "G9L5yLFjti0QTHhPyFrZCT1V/MMnBtXKmoiKDZ78NDBjERki6ZTQZdSMCtkgoNmp17By9ItJr8o7ChX0XxY91nk=",
		"message": "This is an example of a signed message.",
		"address": "1HZwkjkeaoZfTSaJxDw6aKkxp45agDiEzN"
	},
	"amountEur": 200,
	"telegramUser": "@tiero",
	"ttl": "1538611240"
}

Get all sell orders

METHOD

GET  

ENDPOINT

/order/sell?location={"lat":53.272408,"lon":-6.14699}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment