I've spent more time than I care to admit working on my personal website while in lockdown. I've added many useful features like a site search and a stats page but I've also tried to add some fun features too. Today I want to talk about one such feature, the reactions available on my articles.
I was browsing the web searching for useCallback
implementations when I found an article on dev.to. One thing I really like about their article pages is the reactions that sit on the left hand side of the main content. As opposed to a "standard thumbs up reaction", they have opted for a heart and unicorn. As I scroll through the article, the reactions remain sticky and remain on the screen - constantly encouraging interaction with the content. I thought I would attempt to implement a similar component on my personal site.
Emojis and Native Support
In total there are 3,304 emojis in the Unicode Standard, as of March 2020. The most recent emoji release is Emoji 13.0, which added 117 new emojis. Some operating systems support the most modern standard while others lag behind. This means that when using unicode emojis you may find that its appearance varies.
While this is totally fine when texting, you probably are looking for a more consistent experience on your website. The solution I decided to use was react-emoji-render
. In its default use case it will normalise all of the different emoji notations to native unicode characters but you can also tell it to use a particular emoji set like Twemoji which is what I opted for. Same emojis everywhere!
Copied!1.let myEmojiChoice = [2.{ type: "fire", label: "๐ฅ" }, // "It's hot!"3.{ type: "popcorn", label: "๐ฟ" }, // "It's entertaining."4.{ type: "unicorn", label: "๐ฆ" }, // "It's magical."5.{ type: "avo", label: "๐ฅ" }, // "I'm a millennial."6.]
Come scroll with me
It was super important that, on screen sizes that were wide enough, the option to react to the article remained on the screen. In order to achieve that I needed to keep track of the y-scroll position, luckily theres a really cool custom hook I found on npm called react-use-scroll-position
which has a helper function that keeps track of that:
Copied!1.const scrollY = useScrollYPosition();
With this I can then set the position of the element using an in-line style tag:
Copied!1.<div2.style={{3.position: "fixed",4.top: scrollY ? Math.max(20, 335 - scrollY) : 3355.}}6.>7.{Reactions}8.</div>
By using Math.max()
we can ensure that the element starts at the correct place on the side, 335 px down from the top, and only starts following when it is 20px from the top of the window. Cool? Cool.
Keeping track of your reactions
Client-side
Much like a facebook post, I wanted you to be able to react once by clicking the emoji and by clicking it again remove your reaction. If you're interested in mashing buttons you should read this article. I also wanted to ensure that if you left the site and came back your reactions would be remembered. I decided to use window.localstorage
to do this, all wrapped up in a custom hook:
Copied!1.export function useLocalStorage(key, initialValue) {2.const [storedValue, setStoredValue] = useState(() => {3.try {4.const item =5.typeof window !== "undefined"6.? window.localStorage.getItem(key)7.: undefined8.return item ? JSON.parse(item) : initialValue9.} catch (error) {10.console.log(error)11.return initialValue12.}13.})14.const setValue = (value) => {15.try {16.const valueToStore =17.value instanceof Function ? value(storedValue) : value18.setStoredValue(valueToStore)19.typeof window !== "undefined" &&20.window.localStorage.setItem(key, JSON.stringify(valueToStore))21.} catch (error) {22.console.log(error)23.}24.}25.26.return [storedValue, setValue]27.}
When navigating to an article I instatiate this hook:
Copied!1.const [likes, setLikes] = useLocalStorage("likes", {})
Then when incrementing likes, I can check if there are any existing likes for this content and if not then set the reactions of that type to 1.
Copied!1.const incrementLikes = (type) => {2.let contentLikes = likes && likes[contentID] ? likes[contentID] : {}3.if (!contentLikes[type] || contentLikes[type] < 1) {4.setLikes({ ...likes, [contentID]: { [type]: 1 } })5.}6.}
A similar approach was taken for decrementing likes.
Global
I use a firebase firestore to keep track of the reactions made by all users. I wont go into detail about setting up a gatsby project to use firebase here but gatsby-plugin-firebase
is a great place to start. There's also a great article by Kyle Shelvin that has a very solid introduction to using it. I use that in combination with react-firebase-hooks
to read from the database. I do just want to note that I use the hook "useDocumentOnce" as opposed to "useDocument". This means that it reads the data once when loading the page, instead of continually reading. This reduced the amount of usage my database saw from thousands reads to hundreds of reads and therefore saves me money. The only downside is that the reactions may be out of sync if they are liked by someone else while you are still viewing the page.
Using this implementation I can retrieve reactions for a given article with the following code:
Copied!1.const [value, loading, error] = useDocumentOnce(firebase.firestore().doc(`likes/${contentID}`))
I can use this data to populate the number of reactions of a type under the corresponding emoji. And I can update my incrementLikes
function accordingly:
Copied!1.const incrementLikes = (type) => {2.let contentLikes = likes && likes[contentID] ? likes[contentID] : {}3.// If the firebase store has loaded, there is no error and you have not already reacted.4.if (!loading && !error && (!contentLikes[type] || contentLikes[type] < 1)) {5.setLikes({ ...likes, [contentID]: { ...contentLikes, [type]: 1 } })6.// combine the values retrieved from firebase with your additional reaction.7.setNormalisedValues({8....normalisedValues,9.[type]: normalisedValues[type] + 1,10.})11.// ping the firebase store to increment the reactions for the contentID12.firebase13..firestore()14..collection("likes")15..doc(contentID)16..set(17.{18.[type]:19.value.data() && value.data()[type] ? value.data()[type] + 1 : 1,20.},21.// ensure data is merged so that other reaction types are not overridden22.{ merge: true }23.)24.}25.}
Thats all Folks!
I hope you enjoyed this little insight into how the reactions work, why don't you try one of them out now? Better yet, if you like my content subscribe to my newsletter and I will let you know when I post something new! Always no ads or sponsors.