Implementation of BroadcastChannel API in react to emit and subscribe any messages to a particular channel.
To install, you can use npm or yarn:
$ npm install react-web-broadcast-channel
$ yarn add react-web-broadcast-channel
If you open other tab in your browser, you cant see how the message sent is updated in all tabs.
import React from 'react';
import { useBroadcastChannelEmitter } from "react-web-broadcast-channel"
const TEST_CHANNEL = "TEST_CHANNEL";
export default function App() {
const { emit, data } = useBroadcastChannelEmitter(TEST_CHANNEL);
const sendMessage = () => {
emit(prompt())
}
return(
<div>
<button onClick={sendMessage}>emit event</button>
<h1>{data}</h1>
</div>
)
}
import { useEffect } from "react";
import {
BroadcastSubscriber,
BroadcastEmiter,
useBroadcastChannelEmitter
} from "react-web-broadcast-channel";
function EmitMessageFromA() {
const { emit } = useBroadcastChannelEmitter(TEST_CHANNEL);
const sendMessage = () => {
emit(prompt())
}
return <button onClick={sendMessage}>send message from a</button>
}
function EmitMessageFromB() {
return(
<BroadcastEmiter channel={TEST_CHANNEL}>
{(emit) => {
return <button onClick={() => emit(prompt()) }>
send message from b
</button>
}}
</BroadcastEmiter>
)
}
import { BroadcastSubscriber, useBroadcastChannelSubscribe } from "react-web-broadcast-channel";
function SubscriberA() {
const { data } = useBroadcastChannelSubscribe(TEST_CHANNEL);
useEffect(() => {
console.log(data)
},[data])
return <div>Subscribe from A</div>
}
function SubscriberB() {
return(
<BroadcastSubscriber channel={TEST_CHANNEL}>
{(data) => (
<div>{data}<div>
)}
</BroadcastSubscriber>
)
}