onMessageReceived for channelList in React

In React app, I have integrated the Channel and ChannelList. We have to display the browser notifications on messageReceived, how can we implement this function and need to add &remove the handler properly with . Would someone help me to achieve it?

Hey @satyanarayana_ruppa,

To verify, you’re looking for recommendations on how to show browser notifications when a new message is received via the onMessageReceived() handler?

Hi @Tyler, Sorry for the misunderstandings. I have code to show browser notifications, but I am not sure where to add the onMessageReceived handler when we use Channel and ChannelList UIKit components. but I could fix it by following below approach.

integrate sendbird in react app
render Channel&ChannelList components.
when sendbird sdk is ready(not undefined), add the handler in useEffect.

Thanks for your response

onMessageReceived is not related to those UIKit React components. It’s part of the main Chat SDK under ‘ChannelHandler’

In one of your components that is a child of <SendBirdProvider> use the following code.

  const sendbirdContext = useSendbirdStateContext();
  const sb = sendBirdSelectors.getSdk(sendbirdContext);

  const channelHandler = new sb.ChannelHandler();
  channelHandler.onMessageReceived = function (channel, message) {
    console.log('onMessageReceived!', channel, message);
    // send browser notif!
  };

For everyone who is stumbling into this now in mid-2023, this is what works for me:

import { useEffect } from "react";

import Channel from "@sendbird/uikit-react/Channel";
import GroupChannelHandler from "@sendbird/uikit-react/handlers/GroupChannelHandler";

import useSendbirdStateContext from "@sendbird/uikit-react/useSendbirdStateContext";
import sendbirdSelectors from "@sendbird/uikit-react/sendbirdSelectors";

export function CustomChannel({ channelUrl, onMessageReceived }) {
  const sendbirdContext = useSendbirdStateContext();
  const sdk = sendbirdSelectors.getSdk(sendbirdContext);

  useEffect(() => {
    if (!sdk || !sdk.groupChannel) return;
    let UNIQUE_HANDLER_ID = "some_unique_id";
    const groupChannelHandler = new GroupChannelHandler();
    sdk.groupChannel.addGroupChannelHandler(
      UNIQUE_HANDLER_ID,
      groupChannelHandler
    );
    groupChannelHandler.onMessageReceived = onMessageReceived;
    return () => {
      sdk?.groupChannel?.removeGroupChannelHandler(UNIQUE_HANDLER_ID);
    };
  }, [sdk]);

  return (
    <div className="sendbird-app__wrap">
      <Channel channelUrl={channelUrl} />
    </div>
  );
}
export default CustomChannel;

Key things that helped:

  1. running useEffect upon change to sdk. sdk might not be initialized during first few calls to useEffect.
  2. using GroupChannelHandler and sdk.groupChannel.addGroupChannelHandler is the way to go for v4. I had trouble getting some of the older methods to work (e.g. sdk.ChannelHandler)

Good luck!

1 Like