- Mar 2023
-
blog.bitsrc.io blog.bitsrc.io
-
```js // FromStream component
import { PureComponent } from 'react';
export default class FromStream extends PureComponent { constructor(props) { super(props); this.state = { value: false }; }
componentDidMount() { this.initStream(); }
componentDidUpdate(prevProps) { if (prevProps.stream !== this.props.stream) { this.initStream(); } }
componentWillUnmount() { if (this.unSubscribe) { this.unSubscribe(); } }
initStream() { if (this.unSubscribe) { this.unSubscribe(); this.unSubscribe = null; }
if (this.props.stream) { const onValue = (value) => { this.setState(() => ({ value: map(value) })); }; this.props.stream.onValue(onValue); this.unSubscribe = () => stream.offValue(onValue); }
}
render() { return this.props.children(this.state && this.state.value); } } ```
```js // Date/Time import React from 'react'; import Kefir from 'kefir'; import FromStream from './FromStream';
const dateStream = Kefir.interval(1000).map(() => new Date().toString());
export default () => ( <FromStream stream={dateStream}> {(dateString) => dateString} </FromStream> ); ```
```js // Scroll import React from 'react'; import Kefir from 'kefir'; import FromStream from './FromStream';
const scrolledPercentStream = Kefir.fromEvents(document, 'scroll').map((e) => { const scrollY = window.document.pageYOffset; const scrollHeight = e.target.body.scrollHeight; return scrollY / (scrollHeight - windiw.innerHeight) * 100; });
export default () => ( <FromStream stream={scrolledPercentStream}> {(percent) => ( <div className="bar" style={{ top: <code>${percent}% }}></div> )} </FromStream> ); ```
-