GithubHelp home page GithubHelp logo

gnoff / react-side-effect Goto Github PK

View Code? Open in Web Editor NEW

This project forked from gaearon/react-side-effect

0.0 3.0 0.0 204 KB

Create components whose prop changes map to a global side effect

License: MIT License

JavaScript 100.00%

react-side-effect's Introduction

React Side Effect

Create components whose prop changes map to a global side effect.

Installation

npm install --save react-side-effect

Use Cases

  • Setting document.style.overflow or background color depending on current screen;
  • Firing Flux actions using declarative API depending on current screen;
  • Some crazy stuff I haven't thought about.

How's That Different from componentDidUpdate?

It gathers current props across the whole tree before passing them to side effect. For example, this allows you to create <BodyStyle style> component like this:

// RootComponent.js
return (
  <BodyStyle style={{ backgroundColor: 'red' }}>
    {this.state.something ? <SomeComponent /> : <OtherComponent />}
  </BodyStyle>
);

// SomeComponent.js
return (
  <BodyStyle style={{ backgroundColor: this.state.color }}>
    <div>Choose color: <input valueLink={this.linkState('color')} /></div>
  </BodyStyle>
);

and let the effect handler merge style from different level of nesting with innermost winning:

var BodyStyle = createSideEffect(function handleChange(propsList) {
  var style = {};
  propsList.forEach(function (props) {
    Object.assign(style, props.style);
  });
  
  for (var key in style) {
    document.style[key] = style[key];
  }
});

API

createSideEffect: (onChange: Array<Props> -> (), mixin: Object?) -> ReactComponent

Returns a component that, when mounting, unmounting or receiving new props, calls onChange with props of each mounted instance. It's up to you to reduce them, use innermost values, or whatever you fancy.

Component will have a static dispose() method to clear the stack of mounted instances.
When rendering on server, you must call it after each request.

You can use optional second mixin parameter to specify propTypes, displayName or statics. It will be mixed into the generated component.

Usage

Here's how to implement React Document Title (both client and server side) using React Side Effect:

'use strict';

var React = require('react'),
    createSideEffect = require('react-side-effect');

/**
 * Extract title from a list of each mounted component's props.
 * We're interested in the innermost title, but for other use cases we might want to call `propList.reduce`.
 */
function extractTitle(propsList) {
  var innermostProps = propsList[propsList.length - 1];
  if (innermostProps) {
    return innermostProps.title;
  }
}

var _serverTitle = null;

/**
 * Generate a component that reacts to mounting, onmounting and prop changes by updating document title.
 */
var DocumentTitle = createSideEffect(function handleChange(propsList) {
  var title = extractTitle(propsList);

  if (typeof document !== 'undefined') {
    document.title = title || '';
  } else {
    _serverTitle = title || null;
  }
}, {
  displayName: 'DocumentTitle',

  propTypes: {
    title: React.PropTypes.string.isRequired
  },

  statics: {
    /**
     * Peek at current title (for tests).
     */
    peek: function () {
      return _serverTitle;
    },

    /**
     * Call this on server after each request to get current title.
     */
    rewind: function () {
      var title = _serverTitle;
      this.dispose();
      return title;
    }
  }
});

module.exports = DocumentTitle;

react-side-effect's People

Contributors

gaearon avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.