{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/connect-react-to-channels","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Connect React to Channels\",\n  \"order\": 26,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\", \"phoenix\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Connect React to Channels\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Channels with local state\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Anonymous user channels\")), mdx(\"p\", null, \"As it turns out, it's also not especially difficult to connect React to a Phoenix channel. We're going to connect to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel\"), \", then pass our data in through Redux and render our messages to the page.\"), mdx(\"p\", null, \"We're going to start with our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat\"), \" npm component and handle state locally. Then we'll switch to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat-frontend\"), \" and handle our state with Redux to show how the approaches differ.\"), mdx(\"h2\", null, \"Adding Phoenix.js\"), mdx(\"p\", null, \"Phoenix has recently been added to npm, which makes things a lot easier. Previously, this required copying a file and keeping it in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/vendor\"), \" directory. We don't have to worry about that anymore.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save phoenix\\n\")), mdx(\"h2\", null, \"Configuring your \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"channel\")), mdx(\"p\", null, \"We want access to our socket from the entire \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat\"), \" component so we can push messages when a user has the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChatSidebar\"), \" closed, so we'll connect to the socket on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \". We'll also want to create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"You'll notice we're hard-coding \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:4000\"), \" into our component. When we actually deploy this, we're going to change this out for our actual server.\"), mdx(\"p\", null, \"First we need to get rid of our hard-coded messages from our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChatSidebar\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import { Socket } from \\\"phoenix\\\"\\n\\n...\\n\\nexport class PhoenixChatSidebar extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.closeChat = this.closeChat.bind(this)\\n  }\\n\\n...\\n}\\n\\n\")), mdx(\"p\", null, \"Then we need to configure our channel, which we'll do in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureChannels\"), \" function (explanation below the code).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class PhoenixChat extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      isOpen: false,\\n      input: \\\"\\\",\\n      messages: []\\n    }\\n    this.toggleChat = this.toggleChat.bind(this)\\n    this.configureChannels = this.configureChannels.bind(this)\\n  }\\n\\n  componentDidMount() {\\n    this.socket = new Socket(\\\"ws://localhost:4000/socket\\\")\\n    this.socket.connect()\\n    this.configureChannels(\\\"foo\\\")\\n  }\\n\\n  configureChannels(room) {\\n    this.channel = this.socket.channel(`room:${room}`)\\n    this.channel.join()\\n      .receive(\\\"ok\\\", ({ messages }) => {\\n        console.log(`Succesfully joined the ${room} chat room.`)\\n        this.setState({\\n          messages: messages || []\\n        })\\n      })\\n      .receive(\\\"error\\\", () => {\\n        console.log(`Unable to join the ${room} chat room.`)\\n      })\\n    this.channel.on(\\\"message\\\", payload => {\\n      this.setState({\\n        messages: this.state.messages.concat([payload])\\n      })\\n    })\\n  }\\n\\n  toggleChat() {\\n    this.setState({ isOpen: !this.state.isOpen })\\n  }\\n\\n  render() {\\n    return (\\n      <div>\\n        { this.state.isOpen\\n          ? <PhoenixChatSidebar\\n              input={this.state.input}\\n              messages={this.state.messages}\\n              toggleChat={this.toggleChat} />\\n          : <PhoenixChatButton toggleChat={this.toggleChat} /> }\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"When the component mounts, we're going to initialize the socket and assign it to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.socket\"), \", then call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureChannels\"), \" and pass in a string \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"foo\"), \" to connect us to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:foo\"), \". Obviously, this is jsut a temporary value; soon, we will pass a unique ID.\"), mdx(\"p\", null, \"Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureChannels\"), \", we take the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room\"), \" that we got from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \" and we initiated the channel with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket.channel\"), \". Then we joined the channel with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel.join\"), \". If we receive an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ok\"), \" response, we log success and update our state to include any previous messages, otherwise log the failure.\"), mdx(\"p\", null, \"The second part is a listener for whenever our channel receives a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message\"), \", which is an arbitrary name that we are using to label this kind of action. When a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message\"), \" is received (as you will see later in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleMessageSubmit\"), \" function), we want to add the object to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.messages\"), \". The last thing we need to do is to add the current \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.channel\"), \" so we can manipulate it later.\"), mdx(\"p\", null, \"We also changed our render function to handle an empty \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"messages\"), \" array; if you try to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"map\"), \" over an empty array, you get an error.\"), mdx(\"p\", null, \"Now when you check your browser console, you should see the following.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-md\",\n    \"parentName\": \"pre\"\n  }, \"Succesfully joined the foo chat room.\\n\")), mdx(\"p\", null, \"Our channel is now configured.\"), mdx(\"h2\", null, \"Anonymous users\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" package to create a universally unique identifier for each of our anonymous users.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save uuid\\n\")), mdx(\"p\", null, \"Then we just need to change our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \" function to assign a \", mdx(\"a\", {\n    \"href\": \"https://www.npmjs.com/package/uuid\",\n    \"parentName\": \"p\"\n  }, \"universally unique id\"), \" (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \") or find one that already exists. We're going to store this \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \" and connect to a new room.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import uuid from 'uuid'\\n\\n  ...\\nexport class PhoenixChat extends React.Component {\\n\\n  ...\\n\\n  componentDidMount() {\\n    if (!localStorage.phoenix_chat_uuid) {\\n      localStorage.phoenix_chat_uuid = uuid.v4()\\n    }\\n\\n    this.uuid = localStorage.phoenix_chat_uuid\\n    const params = { uuid: this.uuid }\\n    this.socket = new Socket(\\\"ws://localhost:4000/socket\\\", { params })\\n    this.socket.connect()\\n\\n    this.configureChannels(this.uuid)\\n  }\\n\\n  ...\\n}\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room\"), \".\"), mdx(\"h2\", null, \"Submitting messages\"), mdx(\"p\", null, \"Now we need to change our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"messages.map\"), \" to handle our current anonymous user and handle messages sent to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"input\"), \".\"), mdx(\"p\", null, \"You might notice we've added a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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. \", mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"So keep in mind, this app will not work until we update our model.\")), mdx(\"p\", null, \"We're also changing the values from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.props\"), \", since we're going to pass in all the data from the parent (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat\"), \") component, which is connected to the socket.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class PhoenixChatSidebar extends React.Component {\\n\\n  ...\\n\\n  render() {\\n    const list = !this.props.messages ? null : this.props.messages.map(({ body, id, from }, i) => {\\n      const right = from === localStorage.phoenix_chat_uuid\\n\\n      return (\\n        <div\\n          ref={ref => this[`chatMessage:${i}`] = ref}\\n          key={i}\\n          style={{ ...style.messageWrapper, justifyContent: right ? \\\"flex-end\\\" : \\\"flex-start\\\" }}>\\n          <div\\n            style={right ? style.chatRight : style.chatLeft}>\\n            { body }\\n          </div>\\n        </div>\\n      )\\n    })\\n\\n    return (\\n      <div style={style.client}>\\n        ...\\n        <div style={style.inputContainer}>\\n          <input\\n            onKeyDown={this.props.handleMessageSubmit}\\n            onChange={this.props.handleChange}\\n            value={this.props.input}\\n            type=\\\"text\\\"\\n            style={style.inputBox} />\\n          ...\\n        </div>\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"In order to handle our inputs, we're going to need two additional functions: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleMessageSubmit\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleChange\"), \".\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleMessageSubmit\"), \" will listen for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onKeyDown\"), \" events (if you don't know all the React events you have at your disposal, you should peruse the \", mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/react/docs/events.html\",\n    \"parentName\": \"p\"\n  }, \"docs\"), \") and when the key is the \\\"return\\\" key (which has \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n\\nexport class PhoenixChat extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.handleMessageSubmit = this.handleMessageSubmit.bind(this)\\n    this.handleChange = this.handleChange.bind(this)\\n    ...\\n  }\\n  ...\\n\\n  handleMessageSubmit(e) {\\n    if (e.keyCode === 13 && this.state.input !== \\\"\\\") {\\n      this.channel.push('message', {\\n        room: localStorage.phoenix_chat_uuid,\\n        body: this.state.input,\\n        timestamp: new Date().getTime()\\n      })\\n      this.setState({ input: \\\"\\\" })\\n    }\\n  }\\n\\n  handleChange(e) {\\n    this.setState({ input: e.target.value })\\n  }\\n\\n  ...\\n\\n  render() {\\n    return (\\n      <div>\\n        { this.state.isOpen\\n          ? <PhoenixChatSidebar\\n              handleChange={this.handleChange}\\n              handleMessageSubmit={this.handleMessageSubmit}\\n              input={this.state.input}\\n              messages={this.state.messages}\\n              toggleChat={this.toggleChat} />\\n          : <PhoenixChatButton toggleChat={this.toggleChat} /> }\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"Let's also add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentWillUnmount\"), \" function to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat\"), \" component to disconnect from our socket when we close the window.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  componentWillUnmount() {\\n    this.channel.leave()\\n  }\\n  ...\\n\")), mdx(\"p\", null, \"And now you have (half) a functional anonymous chat client set up. You can send messages and see them log in your Phoenix backend.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat-frontend\"), \". In order to do this, we will have to create a new channel just for our administrator.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Connect React to Channels Channels with local state Anonymous user channels As it turns out, it's also not especially difficult to connect…","frontmatter":{"title":"Connect React to Channels","order":26,"active":true,"free":false,"tech":["react","phoenix"]}}},"pageContext":{"slug":"connect-react-to-channels","prevNode":{"frontmatter":{"title":"Set Up Phoenix Channels","active":true,"free":false,"order":25,"tech":["phoenix"]},"fields":{"slug":"set-up-phoenix-channels"}},"nextNode":{"frontmatter":{"title":"Use Presence to List Active Users","active":true,"free":false,"order":27,"tech":["phoenix"]},"fields":{"slug":"use-presence-to-list-active-users"}}}},"staticQueryHashes":["1723017916"]}