react-entangle v1.0.4
react-entangle
HOC allowing components to communicate without any shared contexts using native BroadcastChannel API
I found the native API amusing and wondered why has not anyone implemented an HOC in react for this.
Here is a draft implementation in react. I am not sure where or how this API should be used in the react ecosystem,
please enlighten me if you find any meaning ful implementation.
Demo
https://aakashrajur.github.io/react-entangle/
Install
npm install --save react-entangle
Usage
App.js
import React, { Component, Fragment } from 'react'; import BroadcastHOC from 'react-entangle'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; import ComponentC from './ComponentC'; import OtherComponent './OtherComponent';
class App extends Component { render () { return ( {({data, emitter}) => } ); } }
> ComponentC.js
```jsx harmony
import React, { Component } from 'react';
class ComponentC extends Component {
constructor(props){
super(props);
this.onClick = this.onClick.bind(this);
}
render() {
let {data} = this.props;
return(
<div className='wrapper'>
<div>{data ? JSON.stringify(data): 'No data'}</div>
<div><button onClick={this.onClick}>Send Message</button></div>
</div>
);
}
onClick() {
this.props.emitter('channel_name', {hello: 'world', any:'complex data'});
}
}
API
channels (prop)
provide channels on which the HOC will listen and emit data to
type: string or array of strings
children
you need to provide a function as a child which will receive data and emitter as arguments
({emitter, data}) => <YourComponent emitter={emitter} data={data}/>
Note
Objects emitted are clones and not references.
Functions and errors cannot be sent over
Further Reading
Licence (MIT)
Feel free to use the source anyhow you want.