NPM Package for a React Component: Part 1

  • Create the chat component
  • Publish to NPM

So now that we have the ability to sign up and login, as well as a basic interface for chat, we need to create the interface for the anonymous customer.

The primary use-case of this app is as an NPM installation on an existing project to add chat functionality. Fortunately, this is really easy for us to do because of React's modular nature.

This piece of the app is gives us the chat functionality that you can easily install on any client and it's the medium through which our potential customers will contact the company representatives. When it's finished, it will look like the images below.

Installing dependencies

The first thing we need to is create a new directory and initialize a new NPM package. This is the same as the last time we initialized NPM. Do not create this directory within the existing phoenix-chat-frontend directory; this is a separate project. So the directory structure will look roughly like the following, with three separate directories:

phoenix-chat
|-- node_modules
|-- dist
|-- src
phoenix-chat-frontend
phoenix-chat-api
$ mkdir phoenix-chat
$ cd phoenix-chat && npm init

Then we're going install babel which will allow us to use React with jsx and ES2015 syntax.

$ npm install --save-dev babel-cli babel-preset-react \
babel-preset-es2015 babel-preset-stage-0

Then, just as we did with our frontend app, we need to add Babel presets to package.json.

...
"devDependencies": {
...
},
"babel": {
"presets": [
"es2015",
"react",
"stage-0"
]
}
...

Creating the PhoenixChat component

Now we need to create our PhoenixChat component. We will start with the fixed-position chat bubble in the bottom right, then build out the chat interface.

To start, we need a jsx file and a style.js file that will contain out style object. You may recall from an earlier section that there are many ways to import styles in React. For this project, we are going to use inline-styling.

$ mkdir src dist
$ touch src/{PhoenixChat.jsx,style.js,README.md} README.md

And since placeholder content is boring, lets add a chat image. At some point, you should upload your own image to S3 and use that URL for static asset hosting, but for now, we'll just use Github and a filter to turn the image white.

Then let's create the chat bubble component.

import React from "react"
import style from "./style.js"
export class PhoenixChat extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div style={style.chatButton}>
<img
src="https://github.com/LearnPhoenix/graphics/blob/master/phoenix-chat-icon.png?raw=true"
style={style.chatImage}
/>
</div>
)
}
}
export default PhoenixChat

Then we need to add styling to this component within our style.js file. We're just going to use pure JavaScript styling, both because it's worth knowing how to do and because it's quick and easy.

export const style = {
chatButton: {
position: "fixed",
right: "20px",
bottom: "20px",
background: "rgb(58, 155, 207)",
color: "white",
zIndex: "1000",
height: "60px",
width: "60px",
border: "1px solid #ccc",
borderRadius: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
cursor: "pointer",
boxShadow: "2px 4px 2px -2px rgba(0,0,0,0.3)",
},
chatImage: {
display: "block",
height: "40px",
width: "40px",
filter: "invert(100%)",
WebkitFilter: "invert(100%)",
MozFilter: "invert(100%)",
},
}
export default style

Connecting in development

Before we can check to make sure this works properly, we have to change around a few things in our package.json file and link this package to our existing frontend (at least temporarily).

We're going to add two scripts to package.json, and change the main import file. The first, watch, will watch for changes and automatically compile your code as you go. This is what you'll have running while in development. build will prepare the app for production, and version prepares the next version for deployment.

We are also changing the import file to dist/phoenix-chat.js, which is where our babel command line tool will output the resulting file.

...
"main": "./dist/PhoenixChat.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "babel src --watch --out-dir dist",
"build": "babel src --out-dir dist"
},

Now that we have our package ready, it's time to link it to our phoenix-chat-frontend. We can use npm link to create a globally-installed symbolic link that you can use to locally install the package in a different app. First let's build the package.

$ npm run build

Then we're going to create an npm link between our package and our node_modules for our phoenix-chat-frontend. Do this by running npm link within the phoenix-chat directory to create the global module, then running npm link phoenix-chat from within phoenix-chat-frontend to link the module.

$ npm link
$ cd ../phoenix-chat-frontend
$ npm link phoenix-chat

Unfortunately with the current version of npm this will not work, because two copies of React will end up being installed and you won't be able to use refs (see this specific issue if you are interested). According to the docs, this is intentional, but it's an easy fix with webpack. Within phoenix-chat-frontend, add the following to your webpack configuration:

...
resolve: {
extensions: [ '', '.js' ],
fallback: path.join(__dirname, "node_modules")
},
resolveLoader: {
fallback: path.join(__dirname, "node_modules")
},
...

Now if you look in your node_modules directory within your frontend app, you should see a phoenix-chat module installed. Keep in mind that if you npm prune or re-download this repo, you will have to re-link this package since it wont be downloaded from an npm install.

Now we're going to run the phoenix-chat-frontend and add this component to our Home component.

import PhoenixChat from "phoenix-chat"
export class Home extends React.Component {
...
render() {
if (this.props.user.email) {
return (
<Chat>
<PhoenixChat />
</Chat>
)
}
return (
<div className={style.leader}>
<h1 className={style.title}>Phoenix Chat</h1>
{ this.state.formState === "signup" ? <Signup /> : null }
{ this.state.formState === "login" ? <Login /> : null }
{ this.renderToggleContent() }
<img
role="presentation"
className={style.circles}
src="/learnphoenix-static-assets/images/circles-full.png" />
<PhoenixChat />
</div>
)
}
...
}

Obviously, in the long-run, there is no reason to have an anonymous chat window on the same screen as the administrator, since he would be anonymously messaging himself, but this makes testing a lot easier.

Now you should see the chat bubble appear in the bottom right.

From here, we can continue working on our npm module while watching our changes take effect in realtime. Within the phoenix-chat directory, run the watch command to keep your project updated as you make changes.

$ npm run watch

But this component isn't really all that useful, since it's just a button that doesn't do anything. In the next lesson, we'll add some more functionality.

Previous: Check Login StatusNext: NPM Package for a React Component: Part 2