Thursday, January 5, 2017

What's New in iOS 10? Find Out in This Short Course

WTCS

Hubnest created a new site map, automated the student application process, built a custom communications platform, and implemented a fully responsive design.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Kobalt – a Kirby CMS theme

A lightweight Kirby theme built to help you present yourself and your kool projects to the world in minutes.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Car Dealer – Car Dealer Template

Car Dealer is the most enticing, creative, modern and multipurpose auto dealer Premium HTML5 template suitable for any car dealer websites, business or corporate websites. The template has been Created especially for automotive dealers car resellers.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Legal Services

Estate Connection can assist in numerous aspects of this process and help remove the burden from the shoulders of your loved ones.There lawyers can help you apply for grants, resolve any issues surrounding an existing will, and prepare for litigation


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

This week's JavaScript news, issue 316

This week's JavaScript newsRead this e-mail on the Web
JavaScript Weekly
Issue 316 — January 5, 2017
An accessible hands-on look at using Flow, the static type checker, and integrating it with a Babel workflow.
Jack Franklin

Isomorphic, modular, provides a React-like API, and clocks in at 9KB. It’s slightly larger than Preact but claims better performance.

Functional programming continues to be a hot topic in the JavaScript world. Eric Elliott covers what you need to know.
Eric Elliott

ForwardJS
Nine days of in-person workshops on Angular 2, React, WebVR, Redux, Async, D3, WebPerf, Ionic, TypeScript and Halogen presented by industry experts this March in San Francisco. Early bird tickets are almost gone
ForwardJS   Sponsor

Spoiler alert: it’s Vue.js, Svelte, and Conditioner.js (a conditional module loader).
Tim Severien

A straightforward, good looking, vanilla date and time picker. Also available as Vue.js, React, Ember and Angular components/addons.

Works in both the browser and on Node and uses the highest resolution timing options available.
Nolan Lawson

A guide, adapted from Robert C. Martin’s book Clean Code, to producing readable, reusable, and refactorable software in JavaScript.
Ryan McDermott

A detailed introduction to how you can think about TypeScript, and its ability to improve JavaScript development.
James Henry

Serious about performance for the web? Benedikt argues that we need to start judging browsers “by real world performance and not their ability to game four year old benchmarks”.
Benedikt Meurer

Jobs Supported by Hired.com

  • Web Platform Architect at Twitch (SF)Join the Twitch JavaScript team as a Web Platform Architect and help define our next gen React web platform that scales across our distributed product engineering org while achieving a highly performant web experience!  Twitch
  • Sr. Full Stack Engineer - React/Node (Remote First/Bay Area)We're profitable, growing rapidly and future-proofing with a ground-up build of our long-term platform using React/Redux/Node/CSS in JS. Be a founding member. Healthline.com

Can't find the right job? Want companies to apply to you? Try Hired.com.

In Brief

Migrating A Legacy Frontend Build System to Webpack tutorial
Chang Wang

Build a React App with User Login and Authentication tutorial
Robin Orheden

The 5 Things You Need To Know To Understand React tutorial
Sacha Greif

Webinar: Why ReactJS is Game-Changing for Customer Experiences rawurl
Learn why React creates powerful, consistent customer experiences across all mobile and desktop.
Rangle.io  Sponsor

How My 10-Year-Old Learned JavaScript story
“It was a long journey with many bumps in the road”
Rich Klein

A (Very Quick) Introduction to ES6 Proxies video
Kent C. Dodds

Exploring Functional JavaScript (via 6 Great Talks) video
Grzegorz Ziółkowski

3 Questions to Watch Out For in a JavaScript Interview opinion
Daniel Borowski

10 Reasons I Love create-react-app opinion
Peter Bengtsson

The Web Bluetooth Module for Angular tools
Wassim Chegham

5 jQuery Print Page Options tools
Simon Codrington

Shrimpit: CLI Analysis Tool for Checking Unused JS and JSX ES6 Exports tools
Davy Duperron

eventstop: A Minimal Event Library for Node.js and Browser code
Egoist

Trae: A Minimalistic Fetch-Based HTTP Client for the Browser code
Nicolas Del Valle and Christian Gill

A JS Implementation of Python's range() Function. code
Michał Perłakowski

HTML5 Canvas Gauges (radial, linear, etc.) code
Mykhailo Stadnyk

TexGen.js: Procedural Texture Generation code

Zoom.js: Medium's Image Zoomer, with No Dependencies code
Nishanth Shanmugham

Curated by Peter Cooper and published by Cooperpress.

Like this? You may also enjoy: FrontEnd Focus : Node Weekly : React Status

Stop getting JavaScript Weekly : Change email address : Read this issue on the Web

© Cooperpress Ltd. Office 30, Lincoln Way, Louth, LN11 0LS, UK


by via JavaScript Weekly

Build a React.js Application with User Login and Authentication

Real-life user authentication

This article was originally published on Stormpath. Thank you for supporting the partners who make SitePoint possible.

React (sometimes referred to as React.js) is an awesome way to build web UIs. The Stormpath React SDK extends React and React Router with routes and components that allow you to solve common user management tasks using Stormpath, such as authentication and authorization.

Lately, React has picked up quite some attention, and it's easy to understand why. React allows you to turn complex UIs into simple and reusable components that can be composed easily together.

This post will show you how to build a React application from scratch, using the Stormpath React SDK to add features that allow people to sign up, log in, and even view their own user profile.

Let's get started!

The React + Express.js Application Stack

Since we're building our app from scratch, we'll use ES6 and JSX to write as little code as possible, as well as the Stormpath React SDK for user features.

To give you a good overview of what we'll be using:

  • React - Allows us to compose simple yet powerful UIs.
  • ReactRouter - Organizes the URL navigation in our React application.
  • ES6 - The next version of JavaScript. Allows us to write real JavaScript classes.
  • JSX - Allows us to place HTML in JavaScript without concatenating strings.
  • Stormpath - Allows us to store and authenticate users without having to create our own backend for it.
  • Stormpath React SDK - Integrates registration forms, login pages and authentication into our React application with very little effort.
  • Express - Allows us to serve our HTML and JavaScript files.
  • Express Stormpath - Allows us to serve Stormpath's API through Express.
  • Webpack - Allows us to pack all of our JavaScript files into one bundle.
  • Babel - Allows us to transpile our ES6 and JSX into ES5.
  • Bootstrap - Because we want things to be pretty.

Setting up Our React + Express.js Project

Start by creating a new project directory and a package.json file for it.


$ mkdir my-react-app
$ cd my-react-app
$ npm init --yes

Now install Express, the Stormpath module for Express, and Body Parser:


$ npm install --save express express-stormpath body-parser

We need a server to host our application, so create a new file named server.js and put the code below in it:


var express = require('express');
var stormpath = require('express-stormpath');
var bodyParser = require('body-parser');

var app = express();

app.use(stormpath.init(app, {
  web: {
    produces: ['application/json']
  }
}));

app.on('stormpath.ready', function () {
  app.listen(3000, 'localhost', function (err) {
    if (err) {
      return console.error(err);
    }
    console.log('Listening at http://localhost:3000');
  });
});

Awesome. Now we can hook that up to a Stormpath Application by creating a new file named stormpath.yml with the following code in it. And yeah, you do have to replace those values in it with your own.


client:
  apiKey:
    id: YOUR_API_KEY_ID
    secret: YOUR_API_KEY_SECRET
application:
  href: http://ift.tt/2buVlTO <-- YOUR APP HREF

So far so good. Now try the server by running $ node server.js. If everything is set up correctly then you should see:


Listening at http://localhost:3000

If you saw that message, you've successfully configured your server to talk with Stormpath and expose a REST API for our React application to use.

Configuring Webpack

Before you get too excited, kill the server and install Webpack so that we can package all of our client-side scripts (we'll need this organization soon).


$ npm install --save webpack
$ npm install --save-dev webpack-dev-middleware

Configure Webpack by creating a new file named webpack.config.js and put the code below in it:


var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    './src/app'
  ],
  devtool: 'eval-source-map',
  output: {
    path: __dirname,
    filename: 'app.js',
    publicPath: '/js/'
  },
  module: {
    loaders: []
  }
};

What this will do is look in our /src/ directory (that we'll create shortly) and package all of the scripts and their dependencies under that directory as one module. Then use the file /src/app.js and its exports as the export of that module. Then finally when it has generated that module package, it will serve that through Express under the /js/app.js endpoint.

But in order for Express to serve Webpack files, we have to open up server.js and add these lines to the top of it:


var webpack = require('webpack');
var config = require('./webpack.config');

Then immediately after the line var app = express(); add:


var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

As I mentioned before, this will allow Webpack to intercept requests and serve our packaged /js/app.js file.

Configuring Babel

Since we'll be using ES6 and JSX, we need to transpile these files into ES5 (for backwards compatibility with non-modern browsers). This is where Babel comes in. Babel can take our ES6/JSX files as input, and convert those to ES5.

To use Babel, start by installing some dependencies:


$ npm install --save babel-core babel-runtime babel-loader babel-plugin-react-transform \
  babel-preset-es2015 babel-preset-react babel-preset-stage-0

Now we'll instruct Babel on how to compile our files, so create a new file named `.babelrc` and add this code it:


{
  "presets": ["stage-0", "es2015", "react"]
}

Finally, in order to get Babel to work with Webpack, we need to edit `webpack.config.js` and add an entry to the `module.loaders` array, as shown below:


module: {
  loaders: [{
    test: /\.js$/,
    loaders: ['babel'],
    include: path.join(__dirname, 'src')
  }]
}

Index.html and Bootstrap

Now, before getting our hands dirty with React, we'll prepare the entry page for our app. This page will tell the browser what it must load before we initialize React and our application. So create a new directory named build, then within that, put a file named index.html. Our server will serve all of our static files from this folder.


$ mkdir build
$ cd build
$ touch index.html

Then within index.html, put the following:


<!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8"><![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"><!--<![endif]-->
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <base href="/">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="/css/bootstrap.min.css" />
  </head>
  <body>
    <div id="app-container"></div>
    <script src="/js/app.js"></script>
  </body>
</html>

Also, under the build directory, create a new directory named css and download Bootstrap to it. Name the file bootstrap.min.css.


$ mkdir css
$ cd css
$ curl -O http://ift.tt/1jAc5cP
$ cd ../.. # return to /my-react-app

Now in order for our browser to be able to access these files we need to configure them so that they are served through Express. So open up server.js and at the top of the file add:


var path = require('path');

Then under the line app.use(stormpath.init(app, ...)); add:


app.get('/css/bootstrap.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'build/css/bootstrap.min.css'));
});

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build/index.html'));
});

How Does React Work?

Now that we have the skeleton for our app done, we can focus on building our React app. But before we write any code, let's take a look at what React is and what it does for us.

Components

In React, everything is built upon components. You can think of a component as something that renders a DOM node. A simple React component looks like this:


class HelloWorld extends React.Component {
  render() {
    return <span>Hello World!</span>;
  }
}

That was simple. Now, if you wanted to render this component to a page, then all you'd have to do is import React and then call:


ReactDOM.render(
  <HelloWorld />,
  document.getElementById('hello-world-element')
);

And React would render the component to that element.

There are, of course, more things to a React component, such as state. Below is an example of a counter component that starts counting when added to the DOM and stops when removed.


class Counter extends React.Component {
  state = {
    current: 0
  }

  constructor() {
    super(arguments...);
    this.intervalId = null;
  }

  updateCounter() {
    this.setState({ counter: this.state.current + 1 });
  }

  componentWillMount() {
    this.setState({ counter: this.props.from || 0 });
    this.intervalId = setInterval(this.updateCounter.bind(this), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  render() {
    return <span>{ this.state.current }</span>;
  }
}

Notice the methods componentWillMount() and componentWillUnmount(). These are component life-cycle methods that will be executed at various points of a component's life-cycle (in this case, mount and unmount). These methods are usually used for setting up and tearing down a component and is necessary to use because React will error if you try to set the state of a component when it hasn't been mounted yet.

Also notice this.props.from. The member this.props is a collection of all the properties (inputs) passed to a component. Properties of a component can be set as shown below:


<Counter from="50" />
<Counter from={ myVariable } />

JSX Variables

Variables can easily be interpolated into your JSX DOM using { nameOfVariable }, e.g. as shown below:


render() {
  var myVariable = 123;
  return <span>{ myVariable }</span>;
}

JSX and Reserved JavaScript Identifiers

Since JSX is JavaScript, there are some caveats that you need to know when working with React. I.e. when setting properties of a React DOM component you cannot use neither for or class since those are considered reserved JavaScript identifiers. To get around this problem, React has come up with htmlFor and className that you should use instead.

To illustrate the issue, this won't work:


<label for="my-input" class="my-label">My Input</label>

But this will:


<label htmlFor="my-input" className="my-label">My Input</label>

Virtual DOM

Instead of working directly against the DOM, in React all components are kept in their own virtual DOM. You can think of the virtual DOM as a DOM implementation in JavaScript (because it actually is). This virtual DOM is then mapped to a real DOM element. So when you render your React component, React will look at the DOM output from the component, compare it to its representation in the virtual DOM, and then generate a patch for the real DOM.

What this means is that you never have to think of manually manipulating DOM elements again. All you have to do is tell React how you want your component to look like, and it will take care of transforming the DOM the ways necessary (with minimal effort).

Installing React Dependencies

Now when we are acquainted with React, we'll kick things off by installing some React dependencies:


$ npm install --save react react-dom react-router react-stormpath react-document-title history

Before we start coding, we need a place to put our React files, so create a new directory named src, and then use that as your working directory.


$ mkdir src
$ cd src

Now, let's start with the entry point of our app. This will be the place where we will set up our React application and its routing. So create a new file named app.js and enter this code:


import React from 'react';
import ReactDOM from 'react-dom';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';

ReactDOM.render(
  <Router history={browserHistory}>
  </Router>,
  document.getElementById('app-container')
);

So now we have a foundation for our application. Let's go ahead and import the Stormpath SDK and some things we'll need in it. At the top of your app.js file, add the import statement:


import ReactStormpath, { Router, HomeRoute, LoginRoute, AuthenticatedRoute } from 'react-stormpath';

As you can see in app.js there's now two conflicting Router imports. Since ReactStormpath.Router extends from ReactRouter.Router we won't be needing that anymore. So go ahead and remove the Router import from react-router. Important: Leave the other ReactRouter imports, we'll be needing those later.

Now, we'll initialize the Stormpath SDK. Add the following line right above ReactDOM.render().


ReactStormpath.init();

That was easy! We're now ready to start building our pages.

Master Page

Before we create our pages, we have to set up our router. The router is what determines how we'll be able to navigate around in our React application. We'll start by creating a shared root route. This will act as our "master page". I.e. all routes under this route will all share the same master component (header). So place the code below inside the <Router> tag in app.js so that it looks like this:


<Router history={browserHistory}>
  <Route path='/' component={MasterPage}>
  </Route>
</Router>

As you can see, we have referenced MasterPage. Something that doesn't exist yet. So let's go ahead and create that in a new directory that we'll name pages, in our src folder.


$ mkdir pages
$ cd pages

Now create a new file named MasterPage.js and add this code to it:


import React from 'react';
import { Link } from 'react-router';
import { LoginLink } from 'react-stormpath';
import DocumentTitle from 'react-document-title';

import Header from './Header';

export default class is extends React.Component {
  render() {
    return (
      <DocumentTitle title='My React App'>
        <div className='MasterPage'>
          <Header />
          { this.props.children }
        </div>
      </DocumentTitle>
    );
  }
}

As you can see, we don't have a Header component yet, so let's go and create a new file named Header.js in the same directory with the following content:


import React from 'react';
import { Link } from 'react-router';
import { LoginLink, LogoutLink, Authenticated, NotAuthenticated } from 'react-stormpath';

export default class Header extends React.Component {
  render() {
    return (
      <nav className="navbar navbar-default navbar-static-top">
        <div className="container">
          <div id="navbar-collapse" className="collapse navbar-collapse">
            <ul className="nav navbar-nav">
              <li><Link to="/">Home</Link></li>
            </ul>
            <ul className="nav navbar-nav navbar-right">
            </ul>
          </div>
        </div>
      </nav>
    );
  }
}

Index Page

In our MasterPage notice the property this.props.children. This will contain the components of the child routes that our router match. So if we had a route that looked like:

Continue reading %Build a React.js Application with User Login and Authentication%


by Robin Orheden via SitePoint