• Stars
    star
    792
  • Rank 57,492 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A pure component dev starter kit for React.

React Pure Component Starter

Circle CI

React 0.14 introduced the ability to use pure functions as components. The react team calls them functional components in their announcement. The rest of the world calls them pure components.

This repo demonstrates pure components. It's based on the React Transform Boilerplate and features:

  • Examples of pure components.
  • Pure component factories, so you can use a single React instance, even if you load React from CDN.
  • Unit test example with tape, demonstrating an easy way to test pure components.

Getting Started

Clone the repo & install:

git clone [email protected]:ericelliott/react-pure-component-starter.git
cd react-pure-component-starter
npm install

Optionally set environment variables HOST and PORT, start the dev server and follow instructions: As of this writing:

Cloud9 (c9.io) HOST='0.0.0.0' PORT=8080

Nitrous.io HOST='0.0.0.0' PORT=3000

The environment variables can be set locally in bash terminal using export (e.g., export PORT=8080).)

npm start

In another terminal window, start the dev console for lint/test feedback when you save files:

npm run watch

Pure Component Factories

Pure component factories let you inject your React instance into the component so that you can share a single React instance across your entire app -- even if you load React from CDN for client use (which may save lots of users time, because they'll already have it cached locally). To get a better understanding of why this is important see Two Reacts Wonโ€™t Be Friends by Dan Abramov.

I recommend that all your reusable components export factories and take a React instance as a dependency. It's really easy. A regular pure component looks like this:

export default props => <h1>{ props.title }</h1>;

To add the factory wrapper for React injection, just insert another arrow function with a React parameter:

export default React => props => <h1>{ props.title }</h1>;

If you're still confused, this desugars to this ordinary ES5:

"use strict";

module.exports = function (React) {
  return function (props) {
    return React.createElement(
      "h1",
      null,
      props.title
    );
  };
};

Yeah. Arrow functions rock.

In case you blinked and missed it, the ES6 factory again:

export default React => props => <h1>{ props.title }</h1>;

As you can see, React is a parameter, but it doesn't get explicitly mentioned anywhere in the rest of the line... and there are no other lines. So why do we need it?

Remember that JSX is not real DOM markup. There's a compile step that transforms the JSX code into this:

React.createElement(
  "h1",
  null,
  props.title
);

That compiled output uses React, and expects it to be available inside the component scope, so you need to pass React in, even though it's not obvious that it's being used.

Unit Testing React Components

I recommend Test Driven Development (TDD). Write your tests first. Learn how to write unit tests: Read 5 Questions Every Unit Test Must Answer.

Unit testing React components is a lot easier than it sounds. Let's look at the imports for the title example in test/components/title/index.js:

import React from 'react';
import reactDom from 'react-dom/server';
import test from 'tape';
import dom from 'cheerio';

The first line pulls in React, which you'll need to pass into the component factory. As we already mentioned, it's also required for the JSX to work.

react-dom

import reactDom from 'react-dom/server';

React 0.14 split the DOM utilities out of the main React package. There are several reasons for this change. One of the more important reasons is that React is not always used to render HTML DOM. For instance, Netflix uses it to render to an in-house rendering library called Gibbon, and Facebook has another framework called React Native, which lets you build native user interfaces on mobile using JavaScript, sharing much of the same code and architecture with your web and server apps.

So, react's DOM utilities now live in react-dom, which is split in two:

  • react-dom/server
  • react-dom/client

Tape

import test from 'tape';

Tape is a great testrunner because it keeps everything very simple. For details, read Why I Use Tape Instead of Mocha, and So Should You.

Cheerio

import dom from 'cheerio';

Cheerio is a jQuery-like API for querying and manipulating DOM nodes. If you know jQuery, you know Cheerio.

I use it for testing React component outputs. Much better than the peculiarly named .findRenderedDOMComponentWithClass() and .scryRenderedDOMComponentsWithClass() (I swear, I'm not making these up).

It does not need JSDom. It does not need Selenium web driver. It does not need a browser. Not even PhantomJS. Your DOM is just DOM. Save the browser wrangling for your critical path functional tests. Keep your component unit tests simple.

"Simplicity is a feature." ~ Jafar Husain (Netflix, TC39)

Learn JavaScript with Eric Elliott

eejs-screenshot

Join the chat at https://gitter.im/learn-javascript-courses/javascript-questions

An online course series for application developers. Ready to jump in? Learn more.

More Repositories

1

rtype

Intuitive structural type notation for JavaScript.
JavaScript
1,129
star
2

autodux

Automate the Redux boilerplate.
JavaScript
592
star
3

h5Validate

An HTML5 form validation plugin for jQuery. Works on all major browsers, both new and old. Implements inline, realtime validation best practices (based on surveys and usability studies). Developed for production use in e-commerce. Currently in production with millions of users.
JavaScript
577
star
4

moneysafe

Convenient, safe money calculations in JS
JavaScript
452
star
5

credential

Easy password hashing and verification in Node. Protects against brute force, rainbow tables, and timing attacks.
JavaScript
348
star
6

rfx

Self documenting runtime interfaces.
JavaScript
277
star
7

redux-dsm

Declarative state machines for Redux: Reduce your async-state boilerplate.
JavaScript
222
star
8

speculation

JavaScript promises are made to be broken. Speculations are cancellable promises.
JavaScript
197
star
9

irecord

An immutable store that exposes an RxJS observable. Great for React.
JavaScript
192
star
10

the-software-developers-library

The Software Developer's Library: a treasure trove of books for people who love code. Curated by Eric Elliott
192
star
11

react-things

A exploratory list of React ecosystem solutions
174
star
12

express-error-handler

A graceful error handler for Express and Restify applications.
JavaScript
168
star
13

feature-toggle

A painless feature toggle system in JavaScript. Decouple development and deployment.
JavaScript
155
star
14

ogen

Write synchronous looking code & mix synchronous & asynchronous results using generators & observables.
JavaScript
129
star
15

tdd-es6-react

Examples of TDD in ES6 with React
95
star
16

react-hello

A hello world example React app
JavaScript
63
star
17

fluentjs1

Talk - Fluent JavaScript Part 1: Prototypal OO. Learn to code like a JS native. Take advantage of JavaScript's distinguishing features in order to write better code.
JavaScript
53
star
18

neurolib

Neuron emulation tools
JavaScript
52
star
19

the-two-pillars-of-javascript-talk

References from "The Two Pillars of JavaScript" talk
51
star
20

maybearray

Native JavaScript Maybes built with arrays.
JavaScript
49
star
21

qconf

Painless configuration with defaults file, environment variables, arguments, function parameters.
JavaScript
45
star
22

object-list

Treat arrays of objects like a db you can query.
JavaScript
43
star
23

gql-validate

Validate a JS object against a GraphQL schema
JavaScript
33
star
24

bunyan-request-logger

Automated request logging middleware for Express. Powered by Bunyan.
JavaScript
29
star
25

tinyapp

A minimal, modular, client-side application framework.
JavaScript
28
star
26

arraygen

Turn any array into a generator.
JavaScript
28
star
27

dpath

Dot Path - FP sugar for immutables
JavaScript
22
star
28

rootrequire

npm install --save rootrequire # then `var root = require('rootrequire'), myLib = require(root + '/path/to/lib.js');`
JavaScript
19
star
29

siren-resource

Resourceful routing with siren+json hypermedia for Express.
JavaScript
18
star
30

version-healthcheck

A plug-and-play /version route for the Node.js Express framework.
JavaScript
17
star
31

react-easy-universal

Universal Routing & Rendering with React & Redux was too hard. Now it's easy.
JavaScript
16
star
32

odotjs

A prototypal OO library for JavaScript
JavaScript
13
star
33

todotasks

TodoMVC for task runners. Not sure which task runner to use? Take a look at some reference implementations.
JavaScript
12
star
34

react-test-demo

React Test Demo
CSS
12
star
35

react-faves

Favorite React Tools
12
star
36

jiron

Make your API self documenting and your clients adaptable to API changes.
11
star
37

saas-questions

SaaS Questions: The most important questions every SaaS company should have answers to.
10
star
38

applitude

JavaScript application namespacing and module management.
JavaScript
8
star
39

grange

Generate all sorts of values based on a range of numbers.
JavaScript
7
star
40

talks-and-interviews

A list of my talks and interviews.
7
star
41

tinyerror

Easy custom errors in browsers, Node, and Applitude
JavaScript
7
star
42

jQuery.outerHTML

A tiny outerHTML shim for jQuery
JavaScript
6
star
43

connect-cache-control

Connect middleware to prevent the browser from caching the response.
JavaScript
6
star
44

nfdata

NFData - A metadata proposal for NFT interoperability
5
star
45

xforms

xforms
JavaScript
5
star
46

sparkly

Ignite Learning, Inspire Creation
CSS
5
star
47

clctr

Event emitting collections with iterators (like Backbone.Collection).
JavaScript
3
star
48

ofilter

Array.prototype.filter for objects.
JavaScript
3
star
49

rejection

You gotta lose to win.
JavaScript
3
star
50

colab

A project collaboration platform centered on live video streaming and monetization.
CSS
3
star
51

slides-intro-to-js-objects

A basic (and short) overview of objects in JavaScript.
JavaScript
2
star
52

slides-modular-javascript

Modular JavaScript With npm and Node Modules
CoffeeScript
2
star
53

testling-jasmine

run jasmine tests in all the browsers with testling
JavaScript
2
star
54

hifi

Flow based programming for Node services.
1
star
55

resource-acl

An ACL intended for use with express-resource.
1
star
56

pja-guestlist-client

The browser client for Guestlist. A demo app for Programming JavaScript Applications.
JavaScript
1
star
57

course-primer

A primer for the "Learn JavaScript with Eric Elliott" course series. Prerequisite for all courses.
1
star
58

mapall

Given an array of promises, map to a same-ordered array of resolutions or rejections.
1
star
59

pja-sections

Draft sections for "Programming JavaScript Applications"
1
star
60

maybe-assign

Like Object.assign, but skip null or undefined props.
1
star