{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/change-room-and-respond-to-messages","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\": \"Change Room and Respond to Messages\",\n  \"order\": 34,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\"]\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, \"Change Room and Respond to Messages\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Respond to messages\")), mdx(\"p\", null, \"Now that we have the ability to receive messages from our anonymous users, we need to be able to respond to them.\"), mdx(\"h2\", null, \"Responding to messages\"), mdx(\"p\", null, \"In order to respond to messages, we're going to need an input and a way to submit that message. We're going to use a \", mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/react/docs/forms.html#controlled-components\",\n    \"parentName\": \"p\"\n  }, \"controlled input\"), \" to handle our message data. We will cover controlled inputs in greater detail in a future lesson, but for now you can think of them as a way to store values in state rather than in the DOM element itself.\"), mdx(\"p\", null, \"The first function we're adding is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleMessageSubmit\"), \", which we will attach to an event (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"e\"), \") on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onKeyDown\"), \" on our input. If the key that was pressed happens to have the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"keyCode\"), \" of 13, then it's the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"return\"), \" key. If the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"return\"), \" key is pressed, we are currently in a room, and there is currently a value in the input, we push a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message\"), \" to the room channel with the current room, the current value of the input, and a timestamp. Then we reset the input's value.\"), mdx(\"p\", null, \"The second function is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleChange\"), \", which listens for a change to the input field and updates \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.input\"), \" with the new value.\"), mdx(\"p\", null, \"The last function we're adding creates the input element.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class Chat extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      presences: {},\\n      messages: [],\\n      input: \\\"\\\",\\n      currentRoom: \\\"\\\"\\n    }\\n    this.changeChatroom = this.changeChatroom.bind(this)\\n    this.handleMessageSubmit = this.handleMessageSubmit.bind(this)\\n    this.handleChange = this.handleChange.bind(this)\\n  }\\n\\n  ...\\n\\n  handleChange(e) {\\n    this.setState({ input: e.target.value })\\n  }\\n\\n  handleMessageSubmit(e) {\\n    if (e.keyCode === 13 && this.state.currentRoom && this.state.input) {\\n      this.channel.push(\\\"message\\\", {\\n        room: this.state.currentRoom,\\n        body: this.state.input,\\n        timestamp: (new Date()).getTime()\\n      })\\n      this.setState({ input: \\\"\\\" })\\n    }\\n  }\\n  ...\\n\\n}\\n\")), mdx(\"p\", null, \"Then we need to pass along the handler functions to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ChatRoom\"), \" component so we can connect them to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onKeyDown\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onChange\"), \" events of our input.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class Chat extends React.Component {\\n  ...\\n\\n  render() {\\n    return (\\n      <div>\\n        <Sidebar\\n          presences={this.state.presences}\\n          onRoomClick={this.changeChatroom} />\\n        <ChatRoom\\n          input={this.state.input}\\n          currentRoom={this.state.currentRoom}\\n          handleChange={this.handleChange}\\n          handleMessageSubmit={this.handleMessageSubmit}\\n          messages={this.state.messages} />\\n        { this.props.children }\\n      </div>\\n    )\\n  }\\n}\\n\\n..\\n\")), mdx(\"p\", null, \"The next step is to add a basic label to each of our messages so we can tell difference between messages sent from our anonymous users and our admin.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport cssModules from \\\"react-css-modules\\\"\\nimport style from \\\"./style.css\\\"\\n\\nexport class ChatRoom extends React.Component {\\n  ...\\n\\n  renderMessages() {\\n    return this.props.messages.map(({\\n      body,\\n      id,\\n      user_id,\\n      anonymous_user_id\\n    }, i) => {\\n      const from = user_id ? 'Me' : anonymous_user_id.substring(0,10)\\n      const msg = `${from}: ${body}`\\n      return (\\n        <div\\n          ref={ref => { this[`chatMessage:${i}`] = ref }}\\n          key={id}>\\n          { msg }\\n        </div>\\n      )\\n    })\\n  }\\n  ...\\n\\n}\\n...\\n\")), mdx(\"p\", null, \"Now we should add an input box so our admin can respond to messages sent by the anonymous users. We're going to take the event handlers we passed in from our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component and attach them to events in the input box. Recall that when an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onKeyDown\"), \" event is triggered with the return key, the message is submitted.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class ChatRoom extends React.Component {\\n  ...\\n\\n  renderInput() {\\n    if (!this.props.currentRoom) return null\\n    return (\\n      <div className={style.inputWrapper}>\\n        <input\\n          value={this.props.input}\\n          onKeyDown={this.props.handleMessageSubmit}\\n          onChange={this.props.handleChange}\\n          className={style.input} />\\n      </div>\\n    )\\n  }\\n\\n  render() {\\n    return (\\n      <div className={style.container}>\\n        <div\\n          ref={ref => { this.chatContainer = ref }}\\n          className={style.chatWrapper}>\\n          { this.renderMessages(this.props) }\\n        </div>\\n        { this.renderInput(this.props) }\\n      </div>\\n    )\\n  }\\n}\\n\\n...\\n\")), mdx(\"p\", null, \"Let's also add some basic styling to make our input easier to use.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-css\",\n    \"parentName\": \"pre\"\n  }, \".container {\\n  position: relative;\\n  height: 100vh;\\n  margin-left: 300px;\\n}\\n\\n.chatWrapper {\\n  position: relative;\\n  height: calc(100vh - 60px);\\n  padding-left: 20px;\\n  padding-top: 10px;\\n  padding-bottom: 10px;\\n  overflow-y: scroll;\\n}\\n\\n.input {\\n  position: absolute;\\n  bottom: 20px;\\n  left: 20px;\\n  width: calc(100% - 40px);\\n  line-height: 40px;\\n  font-size: 20px;\\n  outline: none;\\n  border: 1px solid #ccc;\\n  border-radius: 3px;\\n  padding-left: 10px;\\n  color: #333;\\n}\\n\")), mdx(\"p\", null, \"Now when you enter information into the input and press \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"return\"), \", you can send messages back to the anonymous user.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Change Room and Respond to Messages Respond to messages Now that we have the ability to receive messages from our anonymous users, we need…","frontmatter":{"title":"Change Room and Respond to Messages","order":34,"active":true,"free":false,"tech":["react"]}}},"pageContext":{"slug":"change-room-and-respond-to-messages","prevNode":{"frontmatter":{"title":"Join Room and Receive Messages","active":true,"free":false,"order":33,"tech":["react"]},"fields":{"slug":"join-room-and-receive-messages"}},"nextNode":{"frontmatter":{"title":"List Active and Inactive Users","active":true,"free":false,"order":35,"tech":["react"]},"fields":{"slug":"list-active-and-inactive-users"}}}},"staticQueryHashes":["1723017916"]}