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 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.

Chat interface

The first thing we need to do is break the button out into its own component called PhoenixChatButton, then create the PhoenixChatSidebar component, and finally tie them together based on user actions.

So first, let's refactor the 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.

export class PhoenixChat extends React.Component {
constructor(props) {
super(props)
this.state = {
isOpen: false,
}
this.toggleChat = this.toggleChat.bind(this)
}
toggleChat() {
this.setState({ isOpen: !this.state.isOpen })
}
render() {
return (
<div>
{this.state.isOpen ? (
<PhoenixChatSidebar toggleChat={this.toggleChat} />
) : (
<PhoenixChatButton toggleChat={this.toggleChat} />
)}
</div>
)
}
}

Now we should create the PhoenixChatButton based on the component we made previously, but with an 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 src/PhoenixChat.jsx if you prefer.

export class PhoenixChatButton extends React.Component {
render() {
return (
<div
onClick={this.props.toggleChat}
style={style.chatButton}>
<img
src="https://github.com/LearnPhoenix/graphics/blob/master/phoenix-chat-icon.png?raw=true"
style={style.chatImage} />
</div>
)
}
}

And finally, we should create the PhoenixChatSidebar component. We're going to include some hard-coded data in the state of this component that we will eventually swap out.

The only thing that might look new is the map under the render function that maps over the dummy data in this.state.chat and creates an array of components. What we're doing is checking which 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.

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.

export class PhoenixChatSidebar extends React.Component {
constructor(props) {
super(props)
this.closeChat = this.closeChat.bind(this)
this.state = {
messages: [
{from: "Client", body: "Test"},
{from: "John", body: "Foo"},
{from: "Client", body: "Bar"}
]
}
}
closeChat() {
this.props.toggleChat()
}
render() {
const list = !this.state.messages ? null : this.state.messages.map((bubble, i) => {
const right = bubble.from === "Client"
return (
<div style={{...style.messageWrapper, justifyContent: right ? "flex-end" : "flex-start"}}>
<div
key={i}
style={ right ? style.chatRight : style.chatLeft }>
{ bubble.body }
</div>
</div>
)
})
return (
...
)
}
}

And then in the final return, under our list, add the following jsx:

...
export class PhoenixChatSidebar extends React.Component {
...
render() {
...
return (
<div style={style.client}>
<div style={style.header}>
<div style={style.logo}>
<img
style={{ height: "40px", paddingRight: "5px" }}
alt="learnphoenix logo"
src="/learnphoenix-static-assets/favicons/favicon-96x96.png" />
<span>PhoenixChat.io</span>
</div>
<div
style={style.close}
onClick={this.closeChat}>
Close
</div>
</div>
<div style={style.chatContainer}>
{ list }
</div>
<div style={style.inputContainer}>
<input
type="text"
style={style.inputBox} />
<div>
100% free by <a href="https://learnphoenix.io">PhoenixChat</a>
</div>
</div>
</div>
)
}
...
}

The last thing we need is styling for this new component. Within style.js, add the following (explained below the code):

export const style = {
...
messageWrapper: {
display: "flex",
flexFlow: "row nowrap"
},
chatRight: {
color: "#666666",
margin: "0.5rem 0",
padding: "1rem",
borderRadius: "5px",
background: "rgb(230, 230, 234)"
},
chatLeft: {
color: "white",
margin: "0.5rem 0",
padding: "1rem",
borderRadius: "5px",
background: "rgb(58, 155, 207)"
},
client: {
width: "350px",
position: "fixed",
zIndex: "1000",
right: "0",
top: "0",
bottom: "0",
background: "rgb(247, 247, 248)",
borderLeft: "1px solid #ccc"
},
header: {
height: "50px",
background: "white",
borderBottom: "1px solid #ccc",
width: "100%",
boxShadow: "0 2px 2px -1px rgba(0,0,0,0.1)",
display: "flex",
justifyContent: "space-around",
alignItems: "center"
},
logo: {
display: "flex",
flexFlow: "row nowrap",
alignItems: "center"
},
close: {
cursor: "pointer"
},
chatContainer: {
padding: "1rem",
overflowY: "auto",
height: "calc(100vh - 130px)"
},
inputContainer: {
position: "absolute",
bottom: "0",
left: "0",
width: "100%",
display: "flex",
flexFlow: "column nowrap",
alignItems: "center",
justifyContent: "space-around",
height: "80px"
},
inputBox: {
width: "90%",
height: "40px",
borderRadius: "5px",
fontSize: "14px",
border: "1px solid #ccc",
paddingLeft: "10px",
outline: "none"
}
}

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.

Auto-scroll

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.

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 refs (docs). We are going to use refs to create a unique identifier for each of our messages so we can auto-scroll to the end of the list.

Think of 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 document.getElementById() to find elements.

The ref that we are adding to each message takes in the index (i) from the map over our 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 0, the newest will have index of this.state.length - 1).

We're also going to add a ref to our chat container (the div that contains all of our messages) so we can select it and change the scroll position.

Also, make sure you bind the map function to the current this context or you will get an error because map has its own context. An alternate approach to using bind is to use the self = this approach.

Note: You will often see refs used as strings, but this is now deprecated in favor of functions.

...
export class PhoenixChatSidebar extends React.Component {
...
render() {
const list = !this.state.messages ? null : this.state.messages.map(({ body, id, from }, i) => {
const right = from === "Client"
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.header}>
<div style={style.logo}>
<img
style={{ height: "40px", paddingRight: "5px" }}
alt="learnphoenix logo"
src="/learnphoenix-static-assets/favicons/favicon-96x96.png" />
<span style={style.title}>PhoenixChat.io</span>
</div>
<div
style={style.close}
onClick={this.closeChat}>
Close
</div>
</div>
<div
ref={ref => this.chatContainer = ref}
style={style.chatContainer}>
{ list }
</div>
...
)
...
}
}

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.

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 componentDidUpdate.

We will start by selecting the last message by finding the ref to message with the index of this.state.messages.length - 1, then we set the chat container's scrollTop to the last element in the list's 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.

...
export class PhoenixChatSidebar extends React.Component {
...
componentDidUpdate() {
if (this.props.messages.length > 0) {
const lastMessage = this[`chatMessage:${this.props.messages.length - 1}`]
this.chatContainer.scrollTop = lastMessage.offsetTop
}
}
...
}

Please note: since our 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.

And since you're likely tracking all of this with git, you should create a .gitignore.

$ touch .gitignore

Include your dist directory and your node_modules, because both of these will be generated dynamically.

dist
node_modules

peerDependencies

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.

"dependencies": {
...
},
"peerDependencies": {
"react": "^15.0.0"
}

And finally, if you'd like to publish this package to npm, it's as simple as following these instructions.

If you choose to go this route, be aware of a few things that might trip you up. Npm will automatically generate a .npmignore file if you do not include one, and by default, this copies your .gitignore. So, if you include dist in your .gitignore, your dist will be ignored by npm and your package won't work. The solution to this is to create an .npmignore file with just the things that npm should ignore:

$ touch .npmignore

This will be basically the same as our .gitignore except we want to make sure that our dist is not ignored.

node_modules

And that's a wrap. We won't touch this again until we connect it to our Phoenix channel.

Previous: NPM Package for a React Component: Part 1Next: Set Up Phoenix Channels