Skip to content

gaearon/react-observable-subscribe

 
 

Repository files navigation

react-observable-subscribe

Subscribe to an Observable declaratively with the <Subscribe>{observable}</Subscribe> component.

Install

npm install --save react-observable-subscribe

Usage

This library's default export is a Subscribe component which you can use in your JSX to declaratively subscribe and render Observable streams. Just pass the observable as the only child to the the component.

You can apply any operators you want to your observable before passing it to <Subscribe>--you don't have to use RxJS, the only requirement is the the observable supports observable[Symbol.observable]() from the TC39 spec. This library doesn't come with any actual Observable implementation itself.

import Subscribe from 'react-observable-subscribe';
// ...other imports

class Example extends Component {
  render() {
    return (
      <div>
        <div>
          <h3>Every 100ms:</h3>
          <div>
            <Subscribe>{this.props.stream}</Subscribe>
          </div>
        </div>
        <div>
          <h3>Every 1s:</h3>
          <div>
            <Subscribe>{this.props.stream.throttleTime(1000)}</Subscribe>
          </div>
        </div>
        <div>
          <h3>Every 100ms w/ &lt;input&gt; element: </h3>
          <div>
            <Subscribe>
              {this.props.stream.map(
                value => <input value={value} readOnly />
              )}
            </Subscribe>
          </div>
        </div>
      </div>
    );
  }
}

// This Observable will emit an incrementing
// number every 100ms
let stream = Observable.interval(100);
ReactDOM.render(<Example stream={stream} />, container);

ezgif-79206338

The observable can emit simple primitives (e.g. strings, numbers) or you can even emit JSX elements! Each "onNext" just needs to be a single value, arrays are not supported because of React limitations.

When the observable emits new values, only the content inside <Subscribe> will re-render, not the component in which you declare it, so it's very efficient.

Depending on your preferences, you might find it helpful to use a shorter name for Subscribe when you import it. Since it's the default export, what you name it is totally up to you:

import Sub from 'react-observable-subscribe';

// etc

<div>
  <Sub>{stream.throttleTime(1000)}</Sub>
</div>

About

<Subscribe> component to automatically consume observables declaratively in React JSX

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%