Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An example of a react component that uses Ably to publish to and subscribe to a channel
import React from 'react'
import Ably from "ably/promises";
const client = new Ably.Realtime("your-ably-api-key");
export default class AblyMessageComponent extends React.Component {
constructor() {
this.state = { messages: [] };
async componentDidMount() { = await client.channels.get("my-cool-channel");
await => {
console.log("A message was received", message);
this.setState({ messages: this.state.messages });
console.log("You are subscribed");
async componentWillUnmount() {;
console.log("You are unsubscribed");
sendMessage() {{ name: "myEventName", data: { text: "Some random stuff here." } })
render() {
return (
<button onClick={ (e) => this.sendMessage(e) }>Click here to send a message</button>
<h2>Messages will appear here:</h2>
{, index) => (<li key={"item" + index}>{text}</li>))}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment