{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/npm-package-for-a-react-component-part-2","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\": \"NPM Package for a React Component: Part 2\",\n  \"order\": 24,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\", \"npm\"]\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, \"NPM Package for a React Component: Part 2\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Build the chat interface\")), mdx(\"p\", null, \"At this point, our npm package is not especially functional--it's just a button that hovers over the bottom-right of your app. So in order to make it useful, we need to add a chat interface where users can input a message and (eventually) send it to our administrator.\"), mdx(\"h2\", null, \"Chat interface\"), mdx(\"p\", null, \"The first thing we need to do is break the button out into its own component called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChatButton\"), \", then create the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChatSidebar\"), \" component, and finally tie them together based on user actions.\"), mdx(\"p\", null, \"So first, let's refactor the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat\"), \" component so it knows it's state (whether the chat is open or closed) and create a function that toggles the state of the component.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export class PhoenixChat extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      isOpen: false,\\n    }\\n    this.toggleChat = this.toggleChat.bind(this)\\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 toggleChat={this.toggleChat} />\\n        ) : (\\n          <PhoenixChatButton toggleChat={this.toggleChat} />\\n        )}\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"Now we should create the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChatButton\"), \" based on the component we made previously, but with an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onClick\"), \" that toggles the chat sidebar when a user clicks on it. We're going to add this to the same file to keep things simple, but you can create a new file and import this into \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"src/PhoenixChat.jsx\"), \" if you prefer.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export class PhoenixChatButton extends React.Component {\\n  render() {\\n    return (\\n      <div\\n        onClick={this.props.toggleChat}\\n        style={style.chatButton}>\\n        <img\\n          src=\\\"https://github.com/LearnPhoenix/graphics/blob/master/phoenix-chat-icon.png?raw=true\\\"\\n          style={style.chatImage} />\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"And finally, we should create the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChatSidebar\"), \" component. We're going to include some hard-coded data in the state of this component that we will eventually swap out.\"), mdx(\"p\", null, \"The only thing that might look new is the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"map\"), \" under the render function that maps over the dummy data in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.chat\"), \" and creates an array of components. What we're doing is checking which \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"name\"), \" is present and assigning a particular style based on that name (either right or left aligned). Other than that, everything is fairly straightforward with a column of elements.\"), mdx(\"p\", null, \"We're also adding an index as a key. If you get to a point where you have a lot of messages and this causes performance issues, you'll need to assign a unique id to each message and assign the key to that id. But in this case, since we can only add messages and can't remove them, an index is fine.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export class PhoenixChatSidebar extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.closeChat = this.closeChat.bind(this)\\n    this.state = {\\n      messages: [\\n        {from: \\\"Client\\\", body: \\\"Test\\\"},\\n        {from: \\\"John\\\", body: \\\"Foo\\\"},\\n        {from: \\\"Client\\\", body: \\\"Bar\\\"}\\n      ]\\n    }\\n  }\\n\\n  closeChat() {\\n    this.props.toggleChat()\\n  }\\n\\n  render() {\\n    const list = !this.state.messages ? null : this.state.messages.map((bubble, i) => {\\n      const right = bubble.from === \\\"Client\\\"\\n      return (\\n        <div style={{...style.messageWrapper, justifyContent: right ? \\\"flex-end\\\" : \\\"flex-start\\\"}}>\\n          <div\\n            key={i}\\n            style={ right ? style.chatRight : style.chatLeft }>\\n            { bubble.body }\\n          </div>\\n        </div>\\n      )\\n    })\\n    return (\\n      ...\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"And then in the final return, under our list, add the following jsx:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class PhoenixChatSidebar extends React.Component {\\n  ...\\n\\n  render() {\\n    ...\\n\\n    return (\\n      <div style={style.client}>\\n        <div style={style.header}>\\n          <div style={style.logo}>\\n            <img\\n              style={{ height: \\\"40px\\\", paddingRight: \\\"5px\\\" }}\\n              alt=\\\"learnphoenix logo\\\"\\n              src=\\\"/learnphoenix-static-assets/favicons/favicon-96x96.png\\\" />\\n            <span>PhoenixChat.io</span>\\n          </div>\\n          <div\\n            style={style.close}\\n            onClick={this.closeChat}>\\n            Close\\n          </div>\\n        </div>\\n        <div style={style.chatContainer}>\\n          { list }\\n        </div>\\n        <div style={style.inputContainer}>\\n          <input\\n            type=\\\"text\\\"\\n            style={style.inputBox} />\\n          <div>\\n            100% free by <a href=\\\"https://learnphoenix.io\\\">PhoenixChat</a>\\n          </div>\\n        </div>\\n      </div>\\n    )\\n  }\\n\\n  ...\\n}\\n\")), mdx(\"p\", null, \"The last thing we need is styling for this new component. Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"style.js\"), \", add the following (explained below the code):\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export const style = {\\n  ...\\n  messageWrapper: {\\n    display: \\\"flex\\\",\\n    flexFlow: \\\"row nowrap\\\"\\n  },\\n  chatRight: {\\n    color: \\\"#666666\\\",\\n    margin: \\\"0.5rem 0\\\",\\n    padding: \\\"1rem\\\",\\n    borderRadius: \\\"5px\\\",\\n    background: \\\"rgb(230, 230, 234)\\\"\\n  },\\n  chatLeft: {\\n    color: \\\"white\\\",\\n    margin: \\\"0.5rem 0\\\",\\n    padding: \\\"1rem\\\",\\n    borderRadius: \\\"5px\\\",\\n    background: \\\"rgb(58, 155, 207)\\\"\\n  },\\n  client: {\\n    width: \\\"350px\\\",\\n    position: \\\"fixed\\\",\\n    zIndex: \\\"1000\\\",\\n    right: \\\"0\\\",\\n    top: \\\"0\\\",\\n    bottom: \\\"0\\\",\\n    background: \\\"rgb(247, 247, 248)\\\",\\n    borderLeft: \\\"1px solid #ccc\\\"\\n  },\\n  header: {\\n    height: \\\"50px\\\",\\n    background: \\\"white\\\",\\n    borderBottom: \\\"1px solid #ccc\\\",\\n    width: \\\"100%\\\",\\n    boxShadow: \\\"0 2px 2px -1px rgba(0,0,0,0.1)\\\",\\n    display: \\\"flex\\\",\\n    justifyContent: \\\"space-around\\\",\\n    alignItems: \\\"center\\\"\\n  },\\n  logo: {\\n    display: \\\"flex\\\",\\n    flexFlow: \\\"row nowrap\\\",\\n    alignItems: \\\"center\\\"\\n  },\\n  close: {\\n    cursor: \\\"pointer\\\"\\n  },\\n  chatContainer: {\\n    padding: \\\"1rem\\\",\\n    overflowY: \\\"auto\\\",\\n    height: \\\"calc(100vh - 130px)\\\"\\n  },\\n  inputContainer: {\\n    position: \\\"absolute\\\",\\n    bottom: \\\"0\\\",\\n    left: \\\"0\\\",\\n    width: \\\"100%\\\",\\n    display: \\\"flex\\\",\\n    flexFlow: \\\"column nowrap\\\",\\n    alignItems: \\\"center\\\",\\n    justifyContent: \\\"space-around\\\",\\n    height: \\\"80px\\\"\\n  },\\n  inputBox: {\\n    width: \\\"90%\\\",\\n    height: \\\"40px\\\",\\n    borderRadius: \\\"5px\\\",\\n    fontSize: \\\"14px\\\",\\n    border: \\\"1px solid #ccc\\\",\\n    paddingLeft: \\\"10px\\\",\\n    outline: \\\"none\\\"\\n  }\\n}\\n\")), mdx(\"p\", null, \"Most of these styles serve to fix the position of the chat element on the right of the screen with everything either fixed or absolutely positioned.\"), mdx(\"h2\", null, \"Auto-scroll\"), mdx(\"p\", null, \"At this point, you have an interface that performs almost as you would expect. You can add messages and they show up on a list. Unfortunately, this list does not know that the bottom is what we want to keep track of. In order to fix this, we need to auto-scroll to the bottom.\"), mdx(\"p\", null, \"Although this seems like something you should be able to do with CSS, you have to use JavaScript to add this functionality. We're going to create a new function and introduce another React feature called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"refs\"), \" \", mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/react/docs/more-about-refs.html\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \". We are going to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"refs\"), \" to create a unique identifier for each of our messages so we can auto-scroll to the end of the list.\"), mdx(\"p\", null, \"Think of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"refs\"), \" as a way of creating a reference to a particular React element. This is generally what you would use in place of something like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"document.getElementById()\"), \" to find elements.\"), mdx(\"p\", null, \"The ref that we are adding to each message takes in the index (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"i\"), \") from the map over our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.messages\"), \" list and assigns that to the name of the reference. That way, when we need to later reference the last item, we can find its relative position in our current messages list (the oldest message will have an index of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"0\"), \", the newest will have index of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.length - 1\"), \").\"), mdx(\"p\", null, \"We're also going to add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ref\"), \" to our chat container (the div that contains all of our messages) so we can select it and change the scroll position.\"), mdx(\"p\", null, \"Also, make sure you bind the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"map\"), \" function to the current \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this\"), \" context or you will get an error because \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"map\"), \" has its own context. An alternate approach to using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"bind\"), \" is to use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"self = this\"), \" approach.\"), mdx(\"p\", null, mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"Note: You will often see \", mdx(\"inlineCode\", {\n    \"parentName\": \"em\"\n  }, \"refs\"), \" used as strings, but this is now deprecated in favor of functions.\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class PhoenixChatSidebar extends React.Component {\\n\\n...\\n\\n  render() {\\n    const list = !this.state.messages ? null : this.state.messages.map(({ body, id, from }, i) => {\\n      const right = from === \\\"Client\\\"\\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    return (\\n      <div style={style.client}>\\n        <div style={style.header}>\\n          <div style={style.logo}>\\n            <img\\n              style={{ height: \\\"40px\\\", paddingRight: \\\"5px\\\" }}\\n              alt=\\\"learnphoenix logo\\\"\\n              src=\\\"/learnphoenix-static-assets/favicons/favicon-96x96.png\\\" />\\n            <span style={style.title}>PhoenixChat.io</span>\\n          </div>\\n          <div\\n            style={style.close}\\n            onClick={this.closeChat}>\\n            Close\\n          </div>\\n        </div>\\n        <div\\n          ref={ref => this.chatContainer = ref}\\n          style={style.chatContainer}>\\n          { list }\\n        </div>\\n      ...\\n    )\\n    ...\\n  }\\n}\\n\")), mdx(\"p\", null, \"So now we have two refs set up. The first will create a new ref for each message and the second will keep a reference to our message list.\"), mdx(\"p\", null, \"From here, we can reference those nodes and set the scroll position. To do that, we need to hook in to our lifecycle method after render and after the DOM is updated because we need the actual DOM values, which we can do with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidUpdate\"), \".\"), mdx(\"p\", null, \"We will start by selecting the last message by finding the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ref\"), \" to message with the index of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.messages.length - 1\"), \", then we set the chat container's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"scrollTop\"), \" to the last element in the list's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"offsetTop\"), \", which sets the scroll position of our list container to the bottom of our last message. Theoretically, this will push our scroll position past the bottom of the container, but it will actually just stop at the bottom of the list container.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class PhoenixChatSidebar extends React.Component {\\n  ...\\n  componentDidUpdate() {\\n    if (this.props.messages.length > 0) {\\n      const lastMessage = this[`chatMessage:${this.props.messages.length - 1}`]\\n      this.chatContainer.scrollTop = lastMessage.offsetTop\\n    }\\n  }\\n  ...\\n}\\n\")), mdx(\"p\", null, mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"Please note:\"), \" since our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"input\"), \" is not currently connected, this will not do anything. But when we connect this component to our channel in a couple lessons and send messages, we will have the auto-scrolling chat component that we expect.\"), mdx(\"p\", null, \"And since you're likely tracking all of this with git, you should create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".gitignore\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch .gitignore\\n\")), mdx(\"p\", null, \"Include your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dist\"), \" directory and your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"node_modules\"), \", because both of these will be generated dynamically.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-text\",\n    \"parentName\": \"pre\"\n  }, \"dist\\nnode_modules\\n\")), mdx(\"h2\", null, \"peerDependencies\"), mdx(\"p\", null, \"For the sake of good housekeeping, let's add React as a peer dependency, so when the package is installed it will note that it requires React in order to work.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"  \\\"dependencies\\\": {\\n    ...\\n  },\\n  \\\"peerDependencies\\\": {\\n    \\\"react\\\": \\\"^15.0.0\\\"\\n  }\\n\")), mdx(\"p\", null, \"And finally, if you'd like to publish this package to npm, it's as simple as following \", mdx(\"a\", {\n    \"href\": \"https://docs.npmjs.com/getting-started/publishing-npm-packages\",\n    \"parentName\": \"p\"\n  }, \"these instructions\"), \".\"), mdx(\"p\", null, \"If you choose to go this route, be aware of a few things that might trip you up. Npm will automatically generate a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".npmignore\"), \" file if you do not include one, and by default, this copies your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".gitignore\"), \". So, if you include \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dist\"), \" in your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".gitignore\"), \", your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dist\"), \" will be ignored by npm and your package won't work. The solution to this is to create an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".npmignore\"), \" file with just the things that npm should ignore:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch .npmignore\\n\")), mdx(\"p\", null, \"This will be basically the same as our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".gitignore\"), \" except we want to make sure that our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dist\"), \" is not ignored.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-text\",\n    \"parentName\": \"pre\"\n  }, \"node_modules\\n\")), mdx(\"p\", null, \"And that's a wrap. We won't touch this again until we connect it to our Phoenix channel.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"NPM Package for a React Component: Part 2 Build the chat interface At this point, our npm package is not especially functional--it's just a…","frontmatter":{"title":"NPM Package for a React Component: Part 2","order":24,"active":true,"free":false,"tech":["react","npm"]}}},"pageContext":{"slug":"npm-package-for-a-react-component-part-2","prevNode":{"frontmatter":{"title":"NPM Package for a React Component: Part 1","active":true,"free":false,"order":23,"tech":["react","npm"]},"fields":{"slug":"npm-package-for-a-react-component-part-1"}},"nextNode":{"frontmatter":{"title":"Set Up Phoenix Channels","active":true,"free":false,"order":25,"tech":["phoenix"]},"fields":{"slug":"set-up-phoenix-channels"}}}},"staticQueryHashes":["1723017916"]}