I’m using React Chat component. Just wanted to kno...
# ask-ai
c
I’m using React Chat component. Just wanted to know how to send and receive the text. Is there any specific hooks or components for that?
t
Thanks for reaching out, Ashish. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To send and receive text using the React Chat component in LiveKit, you can use the
useChat
hook or the pre-built
Chat
component: • Using the
useChat
Hook:
Copy code
function ChatComponent() {
  const { chatMessages, send, isSending } = useChat();

  return (
    
      {chatMessages.map((msg) => (
        
          {msg.from?.identity}: {msg.message}
        
      ))}
      
    
  );
}
◦ The
useChat
hook provides
chatMessages
,
send
, and
isSending
properties. ◦ `chatMessages`: An array of received chat messages. ◦ `send`: A function to send a new message. ◦ `isSending`: A boolean indicating if a message is currently being sent. • Using the
Chat
Component:
Copy code
import { Chat } from '@livekit/components-react';
import '@livekit/components-styles';

export default function Room() {
  return (
    
  );
}
◦ The
Chat
component provides a pre-built UI for chat functionality. ◦ It includes message display, input field, and send button out-of-the-box. Let me know if you need help with specific implementation details! Sources: Add chat to your React app | LiveKit Docs | packages/core/src/observables/dataChannel.ts
c
Can you provide me a basic JavaScript code for sending and receiving messages
t
Here’s a simple JavaScript example to help you send and receive messages using the
useChat
hook:
c
Are theee any hooks or components in react to receive messages.
t
Hey there! If you want to receive messages in a React app using LiveKit, here are a couple of handy hooks you can try out: •
useChat
Hook:
This one’s perfect if you’re focusing on chat features. It gives you a list of received messages through the
chatMessages
property, making it super straightforward.
Copy code
import { useChat } from '@livekit/components-react';

function ChatInterface() {
  const { chatMessages } = useChat();

  return (
    
      {chatMessages.map((msg, index) => (
        
          {msg.from?.identity}: {msg.message}
        
      ))}
    
  );
}
useDataChannel
Hook:
This one’s a bit more flexible—it lets you send and receive messages through a data channel, whether you want to filter by topic or not. Great if you need more control.
Copy code
import { useDataChannel } from '@livekit/components-react';

function MessageReceiver() {
  const { message } = useDataChannel((msg) => {
    console.log("Received message:", msg);
  });

  return (
    
      Latest message: {message?.message}

    
  );
}
So, if you’re building chat-specific stuff,
useChat
is your friend. But if you want more control over messaging,
useDataChannel
has got you covered. Feel free to ask if you want me to help you with anything else!