Chat popups on react, ever reusable components

Hussain Safwan
3 min readSep 11, 2020
Photo by Joshua Ness on Unsplash

Chat popups are pretty fun, let you check your messages out anytime, anywhere, no matter the contents of the parent webpage. In this tutorial we learn how to make one, in pure react, no libraries, no tricks. And the best part? It’s completely reusable, just the make once, use forever type component you need!

Now we gonna divide the task into chunks, primarily into two sections, the lower clickable icon and the upper interactive chatbox. The icons gonna stay there and wait to be pressed, when done so, the chat interface pops up. Here’s a visual;

There are tow states for the chat interface, hidden and visible, so we need to define two style objects and flag, denoting open on close for that. Messages to be displayed are passed as props from the parent, so will be destructured here.

Want to read this story later? Save it in Journal.

Next is to build the JSX. As told earlier, I’ve partitioned the thing into two sections, the icon and the interface. The icon is quite simple with just an image inside. The interface, however, will have a header at the top with the name of the sender. Below that is the message display area, followed by the footer housing input box and the send button icon. Here, have a look;

Messages will be mapped and will be assigned the style whether to adhere to the left or the right on the basis of there parity, for the sake of this tutorial. The following block is placed inside the msg-area div (where the commnet is).

And about the styles, there’s a little I think I should talk about. The entire package is to be wapped inside a div (I mean, that’s how react components export) and that’s an advantage. The wrapper div is to be positioned absolute, so that it appears to be “above” the regular elements on the page and is to be fixed at the lower right corner (like that’s where chats usually appear, you’re free to implement your own thoughts). That’s done assigning a right and a bottom value. And I dont want that to stick to the edge of the page (no puns intended), so I’m gonna give like a 3% border.

And finally, here’s how easy would it b e to call it from a parent component, two props are passed, the messages to be displayed, an array of strings and a function to retrieve the message to be sent when the send button is pressed. Here’s how it all wraps up;

And as always, the entire code is here on gist. Have fun!

📝 Save this story in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--