react-websocket-flux: Building React application with Websocket by Flux architecture.
To setup the package.
npm install react-websocket-flux --save
Use react-websocket-flux to implement your React component.
import { WebsocketStore, WebsocketActions } from 'react-websocket-flux';
export class MyApp extends Component {
constructor(props, context) {
super(props, context);
this.onMessage = this.onMessage.bind(this);
WebsocketActions.connect(this.props.server);
}
componentDidMount() {
WebsocketStore.addMessageListener(this.onMessage);
}
componentWillUnmount() {
WebsocketStore.removeMessageListener(this.onMessage);
}
onMessage(data) {
this.setState(data)
}
render() {
return (
<div>
</div>
);
}
}
Use your React component with server
props.
render(
<MyApp server="wss://wot.city/object/testman/viewer" />,
document.getElementById('content')
);
How to implement your React component with react-websocket-flux.
- Import
WebsocketStore
andWebsocketActions
fromreact-websocket-flux
. - Invoke
WebsocketActions.connect
method to connect to Websocket server. - Invoke
WebsocketStore.addMessageListener
to registeronMessage
listener to Flux store. - Implement
onMessage
listener callback. For ES6, please bindthis
toonMessage
.
The MIT License (MIT). See LICENSE.md.