As it turns out, it's also not especially difficult to connect React to a Phoenix channel. We're going to connect to the channel, then pass our data in through Redux and render our messages to the page.
We're going to start with our phoenix-chat npm component and handle state locally. Then we'll switch to our phoenix-chat-frontend and handle our state with Redux to show how the approaches differ.
Phoenix has recently been added to npm, which makes things a lot easier. Previously, this required copying a file and keeping it in a /vendor directory. We don't have to worry about that anymore.
$ npm install --save phoenixchannelWe want access to our socket from the entire PhoenixChat component so we can push messages when a user has the PhoenixChatSidebar closed, so we'll connect to the socket on componentDidMount. We'll also want to create a configureChannels function to pass in all the configuration options we need. Keep in mind that sockets are lightweight and connecting and disconnecting is not an expensive operation.
You'll notice we're hard-coding localhost:4000 into our component. When we actually deploy this, we're going to change this out for our actual server.
First we need to get rid of our hard-coded messages from our PhoenixChatSidebar.
import { Socket } from "phoenix"...export class PhoenixChatSidebar extends React.Component { constructor(props) { super(props) this.closeChat = this.closeChat.bind(this) }...}Then we need to configure our channel, which we'll do in a configureChannels function (explanation below the code).
...export class PhoenixChat extends React.Component { constructor(props) { super(props) this.state = { isOpen: false, input: "", messages: [] } this.toggleChat = this.toggleChat.bind(this) this.configureChannels = this.configureChannels.bind(this) } componentDidMount() { this.socket = new Socket("ws://localhost:4000/socket") this.socket.connect() this.configureChannels("foo") } configureChannels(room) { this.channel = this.socket.channel(`room:${room}`) this.channel.join() .receive("ok", ({ messages }) => { console.log(`Succesfully joined the ${room} chat room.`) this.setState({ messages: messages || [] }) }) .receive("error", () => { console.log(`Unable to join the ${room} chat room.`) }) this.channel.on("message", payload => { this.setState({ messages: this.state.messages.concat([payload]) }) }) } toggleChat() { this.setState({ isOpen: !this.state.isOpen }) } render() { return ( <div> { this.state.isOpen ? <PhoenixChatSidebar input={this.state.input} messages={this.state.messages} toggleChat={this.toggleChat} /> : <PhoenixChatButton toggleChat={this.toggleChat} /> } </div> ) }}When the component mounts, we're going to initialize the socket and assign it to this.socket, then call configureChannels and pass in a string foo to connect us to room:foo. Obviously, this is jsut a temporary value; soon, we will pass a unique ID.
Within configureChannels, we take the room that we got from componentDidMount and we initiated the channel with socket.channel. Then we joined the channel with channel.join. If we receive an ok response, we log success and update our state to include any previous messages, otherwise log the failure.
The second part is a listener for whenever our channel receives a message, which is an arbitrary name that we are using to label this kind of action. When a message is received (as you will see later in a handleMessageSubmit function), we want to add the object to this.state.messages. The last thing we need to do is to add the current channel to this.channel so we can manipulate it later.
We also changed our render function to handle an empty messages array; if you try to map over an empty array, you get an error.
Now when you check your browser console, you should see the following.
Succesfully joined the foo chat room.Our channel is now configured.
Now that we have the ability to connect to the channel, we're going to need to set this up to handle anonymous users. We're going to use the uuid package to create a universally unique identifier for each of our anonymous users.
$ npm install --save uuidThen we just need to change our componentDidMount function to assign a universally unique id (uuid) or find one that already exists. We're going to store this uuid in localStorage. If one already exists, then we're going to connect to the room with that id. Otherwise, we're going to generate a new id, set that to localStorage and connect to a new room.
import uuid from 'uuid' ...export class PhoenixChat extends React.Component { ... componentDidMount() { if (!localStorage.phoenix_chat_uuid) { localStorage.phoenix_chat_uuid = uuid.v4() } this.uuid = localStorage.phoenix_chat_uuid const params = { uuid: this.uuid } this.socket = new Socket("ws://localhost:4000/socket", { params }) this.socket.connect() this.configureChannels(this.uuid) } ...}And that's all we need to do to handle anonymous users. Refresh and check your browser console and you'll see that you're now connected to a different room.
Now we need to change our messages.map to handle our current anonymous user and handle messages sent to our input.
You might notice we've added a from field, which we do not currently have in our messages. We're going to add this and other fields in the lesson on message persistence. For now, let's just use them as placeholders. So keep in mind, this app will not work until we update our model.
We're also changing the values from this.state to this.props, since we're going to pass in all the data from the parent (PhoenixChat) component, which is connected to the socket.
...export class PhoenixChatSidebar extends React.Component { ... render() { const list = !this.props.messages ? null : this.props.messages.map(({ body, id, from }, i) => { const right = from === localStorage.phoenix_chat_uuid return ( <div ref={ref => this[`chatMessage:${i}`] = ref} key={i} style={{ ...style.messageWrapper, justifyContent: right ? "flex-end" : "flex-start" }}> <div style={right ? style.chatRight : style.chatLeft}> { body } </div> </div> ) }) return ( <div style={style.client}> ... <div style={style.inputContainer}> <input onKeyDown={this.props.handleMessageSubmit} onChange={this.props.handleChange} value={this.props.input} type="text" style={style.inputBox} /> ... </div> </div> ) }}In order to handle our inputs, we're going to need two additional functions: handleMessageSubmit and handleChange.
handleMessageSubmit will listen for onKeyDown events (if you don't know all the React events you have at your disposal, you should peruse the docs) and when the key is the "return" key (which has keyCode number 13), it will send our input to our channel and clear the input. We're also checking to make sure the input value isn't empty.
handleChange listens to changes in our input and changes the value of that input accordingly. This is useful if we decide to implement any sort of validation or text formatting (such as markdown) later on.
...export class PhoenixChat extends React.Component { constructor(props) { super(props) this.handleMessageSubmit = this.handleMessageSubmit.bind(this) this.handleChange = this.handleChange.bind(this) ... } ... handleMessageSubmit(e) { if (e.keyCode === 13 && this.state.input !== "") { this.channel.push('message', { room: localStorage.phoenix_chat_uuid, body: this.state.input, timestamp: new Date().getTime() }) this.setState({ input: "" }) } } handleChange(e) { this.setState({ input: e.target.value }) } ... render() { return ( <div> { this.state.isOpen ? <PhoenixChatSidebar handleChange={this.handleChange} handleMessageSubmit={this.handleMessageSubmit} input={this.state.input} messages={this.state.messages} toggleChat={this.toggleChat} /> : <PhoenixChatButton toggleChat={this.toggleChat} /> } </div> ) }}Let's also add a componentWillUnmount function to our PhoenixChat component to disconnect from our socket when we close the window.
... componentWillUnmount() { this.channel.leave() } ...And now you have (half) a functional anonymous chat client set up. You can send messages and see them log in your Phoenix backend.
The next thing we need to do is give our admin the ability to join this channel so she can respond. This will be done in phoenix-chat-frontend. In order to do this, we will have to create a new channel just for our administrator.