• This repository has been archived on 15/Jul/2019
  • Stars
    star
    247
  • Rank 164,117 (Top 4 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 10 years ago
  • Updated over 9 years ago

Reviews

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

Repository Details

[DEPRECATED] React components and mixins for router related features that work for applications with Fluxible architecture

flux-router-component

Notice: This package is deprecated in favor of fluxible-router.

npm version Build Status Dependency Status devDependency Status Coverage Status

Provides navigational React components (NavLink), router mixin (RouterMixin), and action navigateAction for applications built with Flux architecture. Please check out examples of how to use these components.

Context and Expected Context Methods

Before we explain how to use NavLink and RouterMixin, lets start with two methods they expect:

  • executeAction(navigateAction, payload) - This executes navigate action, switches the app to the new route, and update the url.
  • makePath(routeName, routeParams) - This is used to generate url for a given route.

These two methods need to be available in:

  • the React context of the component (access via this.context in the component), or
  • the context prop of the component (this.props.context)
  • If exists in both this.context and this.props.context, the one in this.context takes higher precedence.

An example of such context is the ComponentContext provided by fluxible-plugin-routr, which is a plugin for fluxible. We have a more sophisticated example application, fluxible-router, showing how everything works together.

Note that React context is an undocumented feature, so its API could change without notice. Here is a blog from Dave King that explains what it is and how to use it.

NavLink

Docs

RouterMixin

Docs

navigateAction

Docs

History Management (Browser Support and Hash-Based Routing)

Considering different application needs and different browser support levels for pushState, this library provides the following options for browser history management:

  • Use History provided by this library (Default)
  • Use HistoryWithHash provided by this library
  • In addition, you can also customize it to use your own

History

This is the default History implementation RouterMixin uses. It is a straight-forward implementation that:

  • uses pushState/replaceState when they are available in the browser.
  • For the browsers without pushState support, History simply refreshes the page by setting window.location.href = url for pushState, and calling window.location.replace(url) for replaceState.

HistoryWithHash

Using hash-based url for client side routing has a lot of known issues. History.js describes those issues pretty well.

But as always, there will be some applications out there that have to use it. This implementation provides a solution.

If you do decide to use hash route, it is recommended to enable checkRouteOnPageLoad. Because hash fragment (that contains route) does not get sent to the server side, RouterMixin will compare the route info from server and route in the hash fragment. On route mismatch, it will dispatch a navigate action on browser side to load the actual page content for the route represented by the hash fragment.

useHashRoute Config

You can decide when to use hash-based routing through the useHashRoute option:

  • useHashRoute=true to force to use hash routing for all browsers, by setting useHashRoute to true when creating the HistoryWithHash instance;
  • unspecified, i.e. omitting the setting, to only use hash route for browsers without native pushState support;
  • useHashRoute=false to turn off hash routing for all browsers.
useHashRoute = true useHashRoute = false useHashRoute unspecified
Browsers with pushState support history.pushState with /home#/path/to/pageB history.pushState with /path/to/pageB Same as useHashRoute = false
Browsers without pushState support page refresh to /home#/path/to/pageB page refresh to /path/to/pageB Same as useHashRoute = true

Custom Transformer for Hash Fragment

By default, the hash fragments are just url paths. With HistoryWithHash, you can transform it to whatever syntax you need by passing props.hashRouteTransformer to the base React component that RouterMixin is mixed into. See the example below for how to configure it.

Example

This is an example of how you can use and configure HistoryWithHash:

var RouterMixin = require('flux-router-component').RouterMixin;
var HistoryWithHash = require('flux-router-component/utils').HistoryWithHash;

var Application = React.createClass({
    mixins: [RouterMixin],
    ...
});

var appComponent = Application({
    ...
    historyCreator: function historyCreator() {
        return new HistoryWithHash({
            // optional. Defaults to true if browser does not support pushState; false otherwise.
            useHashRoute: true,
            // optional. Defaults to '/'. Used when url has no hash fragment
            defaultHashRoute: '/default',
            // optional. Transformer for custom hash route syntax
            hashRouteTransformer: {
                transform: function (original) {
                    // transform url hash fragment from '/new/path' to 'new-path'
                    var transformed = original.replace('/', '-').replace(/^(\-+)/, '');
                    return transformed;
                },
                reverse: function (transformed) {
                    // reverse transform from 'new-path' to '/new/path'
                    var original = '/' + (transformed && transformed.replace('-', '/'));
                    return original;
                }
            }
        });
    }
});

Provide Your Own History Manager

If none of the history managers provided in this library works for your application, you can also customize the RouterMixin to use your own history manager implementation. Please follow the same API as History.

API

Please use History.js and HistoryWithHash.js as examples.

  • on(listener)
  • off(listener)
  • getUrl()
  • getState()
  • pushState(state, title, url)
  • replaceState(state, title, url)

Example:

var RouterMixin = require('flux-router-component').RouterMixin;
var MyHistory = require('MyHistoryManagerIsAwesome');

var Application = React.createClass({
    mixins: [RouterMixin],
    ...
});

var appComponent = Application({
    ...
    historyCreator: function historyCreator() {
        return new MyHistory();
    }
});

Scroll Position Management

RouterMixin has a built-in mechanism for managing scroll position upon page navigation, for modern browsers that support native history state:

  • reset scroll position to (0, 0) when user clicks on a link and navigates to a new page, and
  • restore scroll position to last visited state when user clicks forward and back buttons to navigate between pages.

If you want to disable this behavior, you can set enableScroll prop to false for RouterMixin. This is an example of how it can be done:

var RouterMixin = require('flux-router-component').RouterMixin;

var Application = React.createClass({
    mixins: [RouterMixin],
    ...
});

var appComponent = Application({
    ...
    enableScroll: false
});

onbeforeunload Support

The History API does not allow popstate events to be cancelled, which results in window.onbeforeunload() methods not being triggered. This is problematic for users, since application state could be lost when they navigate to a certain page without knowing the consequences.

Our solution is to check for a window.onbeforeunload() method, prompt the user with window.confirm(), and then navigate to the correct route based on the confirmation. If a route is cancelled by the user, we reset the page URL back to the original URL by using the History pushState() method.

To implement the window.onbeforeunload() method, you need to set it within the components that need user verification before leaving a page. Here is an example:

componentDidMount: function() {
  window.onbeforeunload = function () {
    return 'Make sure to save your changes before leaving this page!';
  }
}

Polyfills

addEventListener and removeEventListener polyfills are provided by:

Array.prototype.reduce and Array.prototype.map (used by dependent library, query-string) polyfill examples are provided by:

You can also look into this polyfill.io polyfill service.

Compatible React Versions

Compatible React Version flux-router-component Version
0.12 >= 0.4.1
0.11 < 0.4

License

This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.

Third-pary open source code used are listed in our package.json file.

More Repositories

1

anthelion

Anthelion is a plugin for Apache Nutch to crawl semantic annotations within HTML pages.
Java
2,841
star
2

mojito

[archiving soon] Yahoo! Mojito Framework
JavaScript
1,570
star
3

boomerang

End user oriented web performance testing and beaconing
JavaScript
1,182
star
4

xss-filters

Secure XSS Filters.
JavaScript
1,079
star
5

flux-examples

Isomorphic Flux examples with Fluxible
1,073
star
6

YangMingShan

YangMingShan is a collection of iOS UI components that we created while building Yahoo apps.
Objective-C
641
star
7

samoa

SAMOA (Scalable Advanced Massive Online Analysis) is an open-source platform for mining big data streams.
Java
426
star
8

dispatchr

A Flux dispatcher for applications that run on the server and the client.
385
star
9

oozie

Oozie - workflow engine for Hadoop
Java
375
star
10

android-range-seek-bar

It provides a SeekBar similar to the default Android one, but with two thumb controls allowing a range to be selected, and some other extras as well.
Java
345
star
11

omid

Transactional Support for HBase (Mirror of https://github.com/apache/incubator-omid)
Java
301
star
12

strip-loader

Webpack loader to strip arbitrary functions out of your production code.
JavaScript
282
star
13

express-state

Share configuration and state data of an Express app with the client-side via JavaScript.
JavaScript
247
star
14

end-to-end

Use OpenPGP-based encryption in Yahoo mail.
JavaScript
223
star
15

swiv

For the open source UI formerly know as Pivot
TypeScript
167
star
16

kobold

Visual regression testing framework, comparing screenshots from multiple builds
JavaScript
153
star
17

Optimal-LSH

This package provides an efficient implementation of locality-sensitve hashing (LSH)
MATLAB
150
star
18

ygloo-ymagine

[archiving soon]
C
140
star
19

rtrace

Rtrace is an x86/x86_64 native code debugger written in Ruby with zero dependencies
Ruby
139
star
20

yos-social-objc

[dormant] Yahoo! Social SDK, an Objective-C library for Mac and iPhone developers.
Objective-C
110
star
21

coname

An experimental cooperative keyserver based on ideas from dename.
Go
107
star
22

crow

Cross-dimensional weighting for aggregated deep convolutional features.
Python
105
star
23

fluxible-router

MOVED TO FLUXIBLE REPO
104
star
24

pngjs-image

JavaScript-based PNG image encoder, decoder, and manipulator
JavaScript
93
star
25

mendel

A build toolchain for experimentation on isomorphic web applications with tree-inheritance and multivariate support.
JavaScript
88
star
26

daytona

An application-agnostic framework for automated performance testing and analysis.
PHP
80
star
27

howl

Common metadata layer for Hadoop's Map Reduce, Pig, and Hive
Java
78
star
28

yos-social-php5

[dormant] Yahoo! Social SDK - PHP5 library
PHP
76
star
29

ypromise

An ES6 Promise polyfill
JavaScript
73
star
30

cronshot

Node module to schedule, take, alter, and store web page screenshots.
JavaScript
69
star
31

yos-social-php

[dormant] Yahoo! Social SDK - PHP library
PHP
68
star
32

yos-social-python

[dormant] Python SDK
Python
62
star
33

gondola

High-performance Raft-based Java Web Container
Java
61
star
34

PyIOCe

Python IOC Editor
Python
60
star
35

Pluton

C++
58
star
36

YaraParser

Yara K-Beam Arc-Eager Dependency Parser
Java
55
star
37

fake-server

Fake-server is a generic and non-intrusive tool used to mock any server response. It has been designed to address issues when running tests against unstable or slow external servers.
JavaScript
54
star
38

csptester

A quick and easy way to test CSP behavior on modern browsers
HTML
49
star
39

storage-lru

An LRU cache to be used with pluggable storage mechanism
JavaScript
47
star
40

messenger-sdk-php

PHP SDK for Yahoo! Messenger API
PHP
46
star
41

secure-handlebars

Handlebars Context Pre-compiler
JavaScript
45
star
42

fs-lock

File restrictions in Node.js
JavaScript
41
star
43

html-purify

HTML5 Purify
HTML
40
star
44

scrollable

React Scrollable
JavaScript
40
star
45

YMPromptKit

YMPromptKit
Objective-C
36
star
46

simplified-lambda

Java
36
star
47

fluxible-plugin-routr

[DEPRECATED] A plugin for fluxible applications to provide routing methods
JavaScript
33
star
48

messenger-sdk

Yahoo! Messenger API SDK
Java
30
star
49

process-watcher

Launch and control your NodeJS processes.
JavaScript
29
star
50

filelogger

filelogger monitors files and sends a copy of every new line to a local or remote syslog
C
28
star
51

mojito-shaker

[archiving soon] Static asset rollup manager for Mojito applications.
JavaScript
27
star
52

locator

A node module that gives semantic meaning to filesystem paths.
JavaScript
24
star
53

mockaccino

A simple Node (and Express.js) server to quickly mock web services responses.
JavaScript
24
star
54

cnet

A wrapper around the Chromium HTTP network stack.
C++
21
star
55

pipr

Tool to pip install missing imports and more
Python
20
star
56

http-filters

Filters for HTTP requests
C++
20
star
57

ACT

ACT.js - Advertising Creative Technology library.
JavaScript
19
star
58

artifactory_ssh_proxy

An ssh proxy for Artifactory
Java
18
star
59

firefoxos-webbing

A template to package web apps for Firefox OS.
JavaScript
18
star
60

xpath_proto_builder

xpath_proto_builder is a library to convert objects (JSON, XML, POJO) into protobuf using xpath notation.
Java
18
star
61

express-yui

Express extension for YUI Applications.
JavaScript
17
star
62

yos-social-java

[dormant] YOS SDK for Java
Java
17
star
63

guerilla

Guerilla is a distributed build/test server specialized for iOS and Android.
JavaScript
17
star
64

spartan

A Scalable Client Authentication & Authorization System for Container-based Environments
JavaScript
17
star
65

Sparkle

Objective-C
16
star
66

express-combo

Combo handler for express applications.
JavaScript
15
star
67

express-secure-handlebars

Express with Secure Handlebars
JavaScript
13
star
68

express-map

Assembles an Express app's route configuration for sharing with the client side via JavaScript.
JavaScript
12
star
69

CocoaSanitizer

A suite of dynamic analysis tools to find bugs at design time. The tools leverage the Objective-C runtime, to look for common anti-patterns which can lead to crashes.
Objective-C
12
star
70

css-js

CSS Parser
JavaScript
11
star
71

express-annotations

Module to augment Express routes with metadata.
JavaScript
11
star
72

node-restrict

Nodejs module that blocks applications from using procss.binding('process_wrap'), process.kill and child_process methods.
JavaScript
11
star
73

extractify

Browserify plugin to extract code to be lazy loaded into separate bundles
JavaScript
10
star
74

bossmashup

Mashup library for Yahoo! Search BOSS
10
star
75

Openstack-EC2

Python
10
star
76

druid-extensions

This repository holds a number of extensions to Druid that we have created at Yahoo.
Java
10
star
77

keyshop

Stub keyserver for the End-to-End extension
Go
9
star
78

formality-classifier

A Python library to predict the formality level of text.
Python
9
star
79

mojito-pipeline

[archiving soon] A rendering scheduler and streamer for Mojito webapps
JavaScript
9
star
80

FlowEtl

This is a framework designed for the creation of testable components which can be interconnected via arbitrary inputs and outputs and those components can be executed in the correct order (inputs satisfied before running) automatically. This is useful since it aids developers in thinking in the paradigm where they plan components ahead of time, allowing for simpler reuse and refactoring later. At yahoo! this was created for a ETL like framework & pipeline, but its applications are not limited to solely that, since the concept itself is generic.
Java
9
star
81

yos-social-as3

[dormant] Yahoo! Social SDK, an ActionScript 3 library for Flash and AIR
ActionScript
9
star
82

locator-handlebars

Handlebars template compiler for locator
JavaScript
7
star
83

yupdates-wordpress

Posts a Yahoo! Update to your connections when you update your WordPress blog.
PHP
7
star
84

metafs

MetaFS is for generating a datastore of file metadata for rapid complex searches
Python
7
star
85

viper

Viper is a utility that returns a live host from a list of host names.
Java
7
star
86

yamall

PLSQL
6
star
87

openstack-ops-tools

Operational tools and utilities for managing openstack
Python
6
star
88

imlost-Android

Random Hack for Kindness project
Java
6
star
89

secure-handlebars-helpers

secure-handlebars-helpers
JavaScript
5
star
90

Image-Builder

Python
5
star
91

node-xlog

JavaScript
5
star
92

locator-lang

Locator plugin to compile language bundles
JavaScript
4
star
93

zeus

Configuration Compiler
C++
4
star
94

memcached-binary

Binary Memcached client for Node.js
JavaScript
4
star
95

cronshot-local

JavaScript
4
star
96

mojito-jscheck

[archiving soon]
JavaScript
4
star
97

mojito-markup-test

[archiving soon]
JavaScript
4
star
98

mojito-rs-hotswap

[archiving soon] Hotswap plugin for Mojito's Resource Store
JavaScript
4
star
99

ygloo

[archiving soon]
4
star
100

yos-social-demo-dotnet

[dormant] A sample implementation of Hybrid OAuth and YQL in .Net
C#
4
star