Getting Started
This section provides a high level overview of the library setup, core components, and how they fit together. It's a great starting point and you can follow along in your code editor. For a complete, step-by-step guide in terms setting up a React project or instructions on creating specific files, see our React Chat tutorial.
#
Your First App with Stream Chat ReactBefore starting, make sure you have installed stream-chat-react
(and stream-chat
), as directed in the
Installation section.
The below example is all the code you need to launch a fully functioning chat experience. The Chat
and Channel
components are React context providers that pass a variety of values to their
children, including UI components, stateful data, and action handler functions.
const App = () => (
<Chat client={client}>
<Channel channel={channel}>
<Window>
<ChannelHeader />
<MessageList />
<MessageInput />
</Window>
<Thread />
</Channel>
</Chat>
);
#
Creating a Chat ClientTo communicate with the Stream Chat API, create an instance of Stream Chat client with your API key and pass via props into the Chat
component. To generate an API key, you can sign up for a free 30-day trial on our website.
Initialize the Stream Chat client:
import { StreamChat } from 'stream-chat';
const client = new StreamChat('your_api_key');
<Chat client={client}>{/** children of Chat component*/}</Chat>;
#
Connecting a UserTokens are used to authenticate a user. Typically, you send this token from your backend to your front end when a user logs in.
See the Tokens & Authentication documentation to learn more
about creating tokens. For our purposes here, we will assume you have created and retrieved a userToken
.
To connect a user, call the connectUser
method on your client instance with the user object and userToken
provided as arguments.
Connect the user directly after instantiating the client to establish a websocket connection with the Stream Chat API. Once the connection
has been opened, your client instance will begin receiving events from the API.
client.connectUser(
{
id: 'dave-matthews',
name: 'Dave Matthews',
},
userToken,
);
#
Creating a ChannelChannels are at the core of Stream Chat. Within a channel you send/receive messages and interact with other users. Once a channel
object has been initialized, the Channel
component consumes the object and renders your chat app's functionality.
By default, the Stream Chat API provides support for five different channel types of varying use cases. A channel type is required when creating a channel and dictates the available features and permissions. The defaults include:
messaging
livestream
team
gaming
commerce
note
You can also create custom channel types and define your own permission sets.
To create an instance of a channel, call the channel
method on your client instance. This method takes the following parameters:
- channel type
- channel ID (optional, will be auto-generated by the backend if not supplied)
- channel data
const channel = client.channel('messaging', {
image: 'dave.png',
name: 'Create a Messaging Channel',
members: ['dave-matthews', 'trey-anastasio'],
// option to add custom fields
});
#
Setting Up the UI ComponentsNow that we have a client instance, a connected user, and a channel, it's time to look at the core components involved in building a fully functioning chat application.
#
ChatThe Chat
component is a React Context provider that wraps the entire Stream Chat application. It provides the ChatContext
to its children, which includes the StreamChat
client instance. All other components within the library must be nested as children
of Chat
to maintain proper functionality.
The client instance can be accessed with our custom context hook:
const { client } = useChatContext();
#
ChannelThe Channel
component is a React Context provider that wraps all of the logic, functionality, and UI for an individual chat channel.
It provides five separate contexts to its children:
ChannelStateContext
- stateful data (ex:messages
ormembers
)ChannelActionContext
- action handlers (ex:sendMessage
oropenThread
)ComponentContext
- custom component UI overrides (ex:Avatar
orMessage
)EmojiContext
- emoji UI components and data (ex:EmojiPicker
oremojiConfig
)TypingContext
- object of currently typing users (i.e.,typing
)
#
ChannelListThe ChannelList
component renders a list of channels and provides a preview for each. Though the ChannelList
is essential in many chat apps,
it isn't a required piece of the library. If a ChannelList
component is used, a channel object should not be placed as a prop on the Channel
component, as the ChannelList
handles channel setting internally.
const App = () => (
<Chat client={client}>
<ChannelList />
<Channel>
<Window>
<ChannelHeader />
<MessageList />
<MessageInput />
</Window>
<Thread />
</Channel>
</Chat>
);
#
WindowThe Window
component handles width changes in the main channel to ensure a seamless user experience when opening and closing a Thread
.
#
ChannelHeaderThe ChannelHeader
displays pertinent information regarding the currently active channel, including image and title.
#
MessageListThe MessageList
component renders a list of messages and consumes the various contexts setup from Channel
. This component accepts a wide variety of optional props for customization needs.
#
MessageInputThe MessageInput
component is a React Context provider that wraps all of the logic, functionality, and UI for the message input displayed in a channel. It provides the MessageInputContext
to its children.
#
ThreadThe Thread
component renders a list of replies tied to a single parent message in a channel's main message list. A Thread
maintains its own state and renders its own MessageList
and MessageInput
components.
#
SummaryIn addition to the above referenced UI components, client instantiation, and user connection, you need little other code to get a fully functioning chat application up and running. See below for an example of the complete code.
note
Remember our Theming and Customizing Components sections in our guides. They offer you a lot of flexibility when adopting our SDK.
import React, { useEffect, useState } from 'react';
import { StreamChat } from 'stream-chat';
import {
Chat,
Channel,
ChannelHeader,
ChannelList,
MessageList,
MessageInput,
Thread,
Window,
} from 'stream-chat-react';
import '@stream-io/stream-chat-css/dist/css/index.css';
const filters = { type: 'messaging' };
const options = { state: true, presence: true, limit: 10 };
const sort = { last_message_at: -1 };
const App = () => {
const [client, setClient] = useState(null);
useEffect(() => {
const newClient = new StreamChat('your_api_key');
const handleConnectionChange = ({ online = false }) => {
if (!online) return console.log('connection lost');
setClient(newClient);
};
newClient.on('connection.changed', handleConnectionChange);
newClient.connectUser(
{
id: 'dave-matthews',
name: 'Dave Matthews',
},
'your_user_token',
);
return () => {
newClient.off('connection.changed', handleConnectionChange);
newClient.disconnectUser().then(() => console.log('connection closed'));
};
}, []);
if (!client) return null;
return (
<Chat client={client}>
<ChannelList filters={filters} sort={sort} options={options} />
<Channel>
<Window>
<ChannelHeader />
<MessageList />
<MessageInput />
</Window>
<Thread />
</Channel>
</Chat>
);
};
export default App;
With a basic chat app up and running with our default UI, it's time to take a deep dive into each individual component in the library.