Using RxJS with React.js: Part 3 — Dispatching events from Component

Using RxJS with React.js: Part 3 - Dispatching events from Component

  • Using RxJS with React.js: Part 3 — Dispatching events from ComponentThis is the third part of the series.Illustration of unidirectional flow between Subject and ComponentUnidirectional cycleEarlier we saw an example of HoC streaming props to the base component.
  • Let’s now look at ways how we can dispatch events from inside the base component, update some value, and the updated value will then be streamed back to the component completing one unidirectional cycle.We can take the example of a form input field.
  • To keep things simple, let’s say BehaviorSubject is a kind of Subject, that can already start with an initial value.import { BehaviorSubject } from ‘rxjs’;const subject$ = new = console.log(x)); // prints `foo` right awayThe base Component with form inputLet’s say this is our base component:import React from ‘react’const MyComponent = React.createClass({ render() { const { value, handleChange } = this.props; return ( div input type=”text” value={value} onChange={e = handleChange(e.target.value)} / pCurrent value: {value}/p /div ); }});From the base component, we are accessing the props value and handleChange.
  • First one is a stream of the input value, and the latter for handling the change.import { BehaviorSubject, Observable } from ‘rxjs’;const formInput$ = new BehaviorSubject(‘foo’); // with initial valueconst handlers$ = Observable.of({ handleChange: value = formInput$.
  • scan(function (props, emitted) { return { …props, …emitted }; });Observing the base ComponentNow that we have the props$ observable ready, we can integrate it with our base complement easily using the observe function from FrintJS:import { observe } from ‘frint-react’;const ObservedRoot = observe(function () { return props$;})(MyComponent);Now you can stream the props, including both the input value and the change handler from your HoC, and also trigger changes in the Subject from your Component’s events.Live demoVisit this example in JSBin.

Earlier we saw an example of HoC streaming props to the base component. Let’s now look at ways how we can dispatch events from inside the base component, update some value, and the updated value will…
Continue reading “Using RxJS with React.js: Part 3 — Dispatching events from Component”

#Reactjs component that renders children elements when they enter the viewport

  • The option allows you to specify how far below, above, to the left, and to the right of the viewport you want to begin displaying your content.
  • The option allows you to specify how far below the viewport you want to begin displaying your content.
  • The option allows you to specify how far to left of the viewport you want to begin displaying your content.
  • The option allows you to specify how far to the right of the viewport you want to begin displaying your content.
  • By default the throttling function is actually a debounce function so that the checking function is only triggered after a user stops scrolling.

react-lazy-load – React component that renders children elements when they enter the viewport.
Continue reading “#Reactjs component that renders children elements when they enter the viewport”

Inspired by the #ReactJS version of Tetris, this amazing adaption is made with Vue #NodeJS

Inspired by the #ReactJS version of Tetris, this amazing adaption is made with Vue

#NodeJS

  • English introduction
    Please view React 版的俄罗斯方块,由于对其实现原理较感兴趣,而且相比于 React 更喜欢 Vue, 于是把 React 版的重构为了 Vue Redux 使用 Vuex Vue + Vuex,其中再加入了 Immutable.js,确保性能和数据可靠性
    1、什么是 Immutable?
    Immutable 是一旦创建,就不能再被更改的数据。对 Immutable 对象的任何修改或添加删除操作都会返回一个新的 Immutable 对象。
    初识:
    让我们看下面一段代码:
    function keyLog(touchFn) {
    let data = { key: ‘value’ };
    f(data);
    console.log(data.key); // 猜猜会打印什么?
    }
    不查看f,不知道它对 data 做了什么,无法确认会打印什么。但如果 data 是 Immutable,你可以确定打印的是 value:
    function keyLog(touchFn) {
    let data = Immutable.Map({ key: ‘value’ });
    f(data);
    console.log(data.get(‘key’)); // value
    }
    JavaScript = {a: 1}; bar = foo; bar.a = 2;
    foo.a // = Immutable.Map({ a: 1 }); bar = foo.set(‘a’, 2);
    foo.get(‘a’) // 1
    关于 b:2, c:3} === {a:1, b:2, c:3}; // false
    [1, 2, [3, 4]] === [1, 2, [3, 4]]; // false
    对于上面只能采用 = Immutable.Map({a:1, b:2, c:3});
    map2 = Immutable.Map({a:1, b:2, c:3});
    Immutable.is(map1, map2); // true

    // List1 = Immutable.List([1, 2, Immutable.List[3, 4]]);
    List1 = Immutable.fromJS([1, 2, [3, 4]]);
    List2 = Immutable.fromJS([1, 2, [3, 4]]);
    Immutable.is(List1, List2); // true
    Immutable学习资料:

    2、Web Audio Audio Audio Api ;
    左右移动可以 delay 掉落的速度,但在撞墙移动的时候 delay 的稍小;在速度为6级时 通过delay 模拟 visibilitychange Vuex ios React 项目重构为 Vue 版本
    Vue 版本和 React 版的 store 使用了 immutable 结构的数据,vuex 上的 store 如果使用了 immutable 结构,不利用监听数据变化,故把store 的数据全部使用了普通的数据,在需要这些数据的地方通过 immutable 提供的 fromJS 转换,在需要普通数据的地方再通过 immutable 的 toJS React 组件改写成 Vue React 的 setState 会触发 render 方法,所以可以在 methods 自定义 render 方法再在 state 变化后手动触发 render 方法

    生命周期,简单来说, React 的 componentWillMount 对应 Vue 的 beforeMount, React 的 componentDidMount 对应 Vue 的 mounted,React 的用来优化性能的 shouldComponentUpdate 在 Vue 里并不需要,不需要手动优化这也是我喜欢 Vue 的一点

    Vue 没有 React 的componentWillReceiveProps 的生命周期,我的解决方法是使用 watch 配合 deep:true 来监听 props 的变化,如:

    watch: {
    $props: {
    deep: true,
    handler(nextProps) {
    //xxx
    }
    }
    }

    在必要时候使用 jsx 和 ‘render’ 函数,是的, vue 支持 jsx,在这个项目中matrix 组件 的功能逻辑较复杂,使用 template 模版来渲染组件已经不合适了, React 每次 setState 会触发 ‘render’ 方法,所以我们可以在 methods自定义 ‘render’ 方法再在 state 变化后手动触发 ‘render’ Vue 的 jsx jsx 语法对页面进行渲染,当 props 或 state 变化了自动触发 ‘render’ 方法,另外要注意的是 vue 的 jsx 和 React 的 jsx 书写上有一点的差异, 当 ‘render’ 方法存在时,template 语法会失效.

  • ‘render’ 函数一个比较实用的用处是在开发类似 React-log 之类的不需要渲染 html 只需要执行一些方法的组件时 template 会显得很多余,因为这时候并不需要渲染 dom 了,如果用了 ‘render’ 函数,简单的在 ‘render’ 函数里 return false 就行,如: react-log

    5、架构差异
    Redux 的数据流向是通过 mapStateToProps 把 store 的状态转化为 props 然后通过connect 函数注入到 根组件,根组件再把这些 props 传入不同组件,当 store 的状态变化,根组件会重新 render, 更新子组件上的 props,子组件再 根据新 props重新 vuex 的思路则不同,任何组件都随时可以通过 this.

  • $store.state.xxx 获取 store 上的数据,更自由,从 store {
    keyboard () {
    return this.store.state.keyboard
    }
    }
    调用 store.commit 提交 payload修改数据 或者 store.dispatch 提交 mutation 间接修改 store 上的数据, commit 和 dispatch 的区别在于 commit 用于同步修改状态, dispatch 用于异步修改状态,异步完成需要再调用 commit,一般简单的需求只需要 commit 一个 payload 就行,只要 store 上的数据变了,组件都会自动重新渲染
    6、开发
    安装
    npm install

    运行
    npm run dev

    浏览自动打开 http://localhost:8080
    多语言
    在 i18n.json run build

    在 dist 文件夹下生成结果。

vue-tetris – Use Vue, Vuex, Immutable to code Tetris.
Continue reading “Inspired by the #ReactJS version of Tetris, this amazing adaption is made with Vue

#NodeJS”

Dealing with focus and blur in a composite widget in React

Dealing with focus and blur in a composite widget in #ReactJS:

  • I put together a silly little pen to illustrate this behavior:A pen from codepen.io that illustrates the order in which keydown, blur, focus and keyup events fire for a tab traversal.
  • So we can listen for focus and blur events at the root of a component and react to these events fired on its child nodes.A GitHub Gist illustrating a very simple React Component for a grid element that responds to blur and focus events.The gist illustrates a React Component that returns a div element with onFocus and onBlur listeners.
  • What the gist intends to demonstrate is how we can toggle the value of the boolean state property isManagingFocus based on blur and focus events that the children of the grid component will fire.The component should:Toggle isManagingFocus to true when an element inside the grid gains focusMaintain isManagingFocus as true as long as an element inside the grid has focusToggle isManagingFocus to false when no element inside the grid has focus.This behavior is achieved by waiting a “tick” on a blur event before toggling the isManagingFocus state to false.
  • The blur and focus events will happen in the same tick (under normal circumstances), allowing the component to cancel its reaction to the blur event if a focus event occurs in the next moment and clears the timeout.
  • If no focus event from an element within the grid occurs (if the user has traversed out of the grid component), then the blur event will be processed in the next tick and the grid component will toggle isManagingFocus to false.Any time we use setTimeout/clearTimeout to manage order of operations, it feels icky.

I ran into a situation a while back while build a table grid component. I need to know when focus left the containing grid component. But the grid itself never receives focus. Its cells are focused…
Continue reading “Dealing with focus and blur in a composite widget in React”

Functional Components in React – ziv zamechek – Medium

Functional Components in React  #javascript #react #reactjs

  • We are setting the state with key term and the new value of the input.
  • The component renders, the value of the input is set to retrieve the value from this.state.term so its initial value is an empty string.
  • Whenever setState is called the event will re render and the value of the input will receive the new value of this.state.term finally the component finishes rendering and the new value of the input is finally visible on the screen.
  • It also allows us to read the value of the input much more easily.The most parent component that is concerned with a piece of information to be responsible for fetching it.
  • Then the callback function with data will be called with the list of videos.The object that we are passing has a key of videos and the value is videos that is passed as an argument.We can condense this using ES6 when key and variable name are the same we can just use the value name which is videos in this case, for example:this.setState({ videos: videos }); is the same as: this.setState({ videos });So the list of videos on the state starts as an empty array but the instance of the component that is rendered kicks off a search when the search is complete it will update the value with the new list of videos.Thank You

So basically the function onChange will run because it is the event handler. We are setting the state with key term and the new value of the input. Whenever we update the state it will cause the…
Continue reading “Functional Components in React – ziv zamechek – Medium”

Its in the a.m. – Montez McCamish – Medium

Its in the a.m.  #inspection #hustle #webdevelopment #react #selfimprovement #reactjs

  • But I woke up felling that I should set out letting others know that this is so true.
  • You are going to have to believe in your self !
  • most of the times your going to have to do alot all by your self, No one is going to care about your dreams as much as you do.
  • I do know that when you show that you have value to others then others will want to gain or help with in the value that you have.the point truly is just this YOU CAN DO ALL THINGS !

Its in the a.m. But I woke up felling that I should set out letting others know that this is so true. You are going to have to believe in your self ! most of the times your going to have to do alot…
Continue reading “Its in the a.m. – Montez McCamish – Medium”

Reducing React jank with (possibly hacky) use of WeakMap

Reducing React jank with (possibly hacky) use of WeakMap  #reactjs #javascript

  • You’ve heard that React’s Virtual DOM implement will help keep your UI snappy and snappy UI is exactly what will give your customers a warm happy glow inside.You’ve just written the first version of your code to test out your ideas:class List extends PureComponent { onClick () { //… } onUpdate (item, updatedValue) { //… } onMouseOver (item) { //… } render () { return ( div onClick={() = this.onClick()} { this.props.items.map((item) = ( Item key={item.id} item={item} onMouseOver={() = this.onMouseOver(item)} onUpdate={(value) = this.onUpdate(item, value)} / )) } /div ) }}class Item extends PureComponent { render () { const { item, onUpdate, …rest } = this.props return ( div {…rest} input type=”text” value={item.value} onChange={(e) = onUpdate(e.target.value)} / /div ) }}You know that React creates a representation of your components and uses it to efficiently update the browser when you provide a new version of this view.You understand that, whilst its generally more than sufficient in most cases, in some cases you want to improve the performance by using PureComponents to tell React which parts have not changed.You’ve put in the key attribute for all your items, which should give a hint to React as to which items match to which.You’ve used ImmutableJS for your state so the shallow compare algorithm that PureComponent uses will be fast and efficient.However you find that its still not helping, and every update still takes longer than you think it should.sooooo slowTo help you debug, you’ve installed the React DevTools for Chrome / Firefox.You click on the little checkbox on the top left corner called ‘Trace React Updates’, which will flash a border around any component that was just updated.With this feature switched on, you notice that, even though you’ve been a good little front-end developer and have done all the performance best practices, each Item is still being updated every time you type.Not what was expectedYou expected that only the Item thats changed should have a flashing border.You search the internet for information and realise, “Duh I’m creating a new function every time I re-render List, even though the item itself didn’t change”.
  • You start by changing the `onClick` handler for the `List` componentclass List extends PureComponent { constructor () { this.onClick = this.onClick.bind(this) } onClick () { //… } //… render () { return ( div onClick={this.onClick} //… /div ) }}Better yet, you remembered there’s the class instance fields proposal, which allows you to define your onClick handler as an arrow function!
  • What to do…You could refactor the Item component so that every event handler is given the item as one of the arguments:class List extends PureComponent { //… render () { return ( div onClick={this.onClick} { this.props.items.map((item) = ( Item key={item.id} item={item} onMouseOver={(e, item) = this.onMouseOver(item)} onUpdate={(item, value) = this.onUpdate(item, value)} / )) } /div ) }}class Item extends PureComponent { render () { const { item, onMouseOver, onUpdate, …rest } = this.props return ( div onMouseOver={(e) = onMouseOver(e, item)} {…rest} input type=”text” onChange={(e) = onUpdate(item, e.target.value)} value={item.value} / /div ) }}Whilst this feels okay for the onUpdate handler, it feels wrong wrapping every possible DOM event handler that the consumer of your Item component could possibly need.You try another approach.
  • This way, only when an item has not been seen before will a new function reference be created:class List extends PureComponent { itemEventHandlers = new WeakMap() getItemEventHandler = (item) { return } const eventHandlers = { onUpdate: (value) = { //… }, onMouseOver: () = { //… } } eventHandlers) return eventHandlers } //… render () { return ( div onClick={this.onClick} { this.props.items.map((item) = ( Item key={item.id} item={item} / )) } /div ) }}You use a WeakMap so you don’t have to manually track when an item is no longer needed and thus its corresponding functions can be garbage collected.
  • Ah the beauty of weak references.You think, “Hey, why not just store the whole Item component instead of just the event handlers so the render function of the List component is even more efficient”:class List extends PureComponent { itemCache = new WeakMap() renderItemComponent = (item) { if(this.itemCache.has(item)){ return this.itemCache.get(item) } const component = ( Item key={item.id} item={item} onUpdate={(value) = {}} onMouseOver={() = {}} / ) this.itemCache.set(item, component) return component } onClick = () { //… } render () { return ( div onClick={this.onClick} { } /div ) }}Your code now does what you expect it to; Each Item updating only if its item has changed.When you go to check React DevTools though, all the `Item` components are still flashing.It works fast now, but DevTools still not showing what you expect.Looking closer, you notice that only the inner icon for the component you’ve changed blinks.

Say you’re building a new application. This application is going to be the thing that updates your company’s product experience to the latest and greatest. You/your designers have mocked up an…
Continue reading “Reducing React jank with (possibly hacky) use of WeakMap”