Alfie Mellor

Alfie Mellor

1566358055

How to show unread message count with React

Originally published by Ayooluwa Isaiah at https://pusher.com

In this tutorial, we’ll go over how this feature works in Chatkit. In the end, you should have a chat app that looks and works like this:

Most chat apps present the unread count for messages in a room somewhere in the application interface. This allows the user to scan the interface and quickly see how many unread messages they have and in what rooms.

Prerequisites

This tutorial assumes prior experience with working with React and Chatkit. If this is your first attempt at using Chatkit, you should probably start here first, then come back to this tutorial at a later time.

You also need to have Node.js (version 8 or later), and npm installed on your machine. Installation instructions can be found on this page.

Sign up for Chatkit

Open this link in a new browser tab, and create a new Chatkit account or sign into your existing account. Once you are logged in, create a new Chatkit instance for this tutorial and take note of your Instance Locator and Secret Key in the Credentials tab.

Also make sure your Test Token Provider is enabled as shown below. One enabled, the endpoint from which the test token will be generated will be displayed for you to copy and paste.

Next, click the Console tab and create a new user and room for your instance. You can follow the instructions on this page to learn how to do so. Once the room has been created, take note of the room ID as we’ll be using it later on.

Create a new React app

Run the command below to install create-react-app globally on your machine, then use it to bootstrap a new react React application:

npm install -g create-react-app 
create-react-app chatkit-unread-messages

Once the app has been created, cd into the new chatkit-unread-messages directory and install the following additional dependencies that we’ll be needing in the course of building the chat app:

npm install @pusher/chatkit-client prop-types skeleton-css --save

You can now start your development server by running npm start then navigate to http://localhost:3000 in your browser to view the app.

Add the styles for the app

Open up src/App.css in your code editor, and change it to look like this:

   // src/App.css

   .App {
     width: 100vw;
     height: 100vh;
     display: flex;
     overflow: hidden;
   }

   .sidebar {
     height: 100%;
     width: 20%;
     background-color: blanchedalmond;
   }

   .login {
     padding: 5px 20px;
   }

   .sidebar input {
     width: 100%;
   }

   .chat-rooms .active {
     background-color: whitesmoke;
     color: #181919;
   }

   .chat-rooms li {
     display: flex;
     align-items: center;
     justify-content: space-between;
     padding: 15px 20px;
     font-size: 18px;
     color: #181919;
     cursor: pointer;
     border-bottom: 1px solid #eee;
     margin-bottom: 0;
   }

   .room-list h3 {
     padding-left: 20px;
     padding-right: 20px;
   }

   .room-unread {
     display: inline-block;
     width: 20px;
     height: 20px;
     line-height: 20px;
     border-radius: 50%;
     font-size: 16px;
     text-align: center;
     padding: 5px;
     background-color: greenyellow;
     color: #222;
   }

   .chat-rooms li:hover {
     background-color: #D8D1D1;
   }

   .chat-screen {
     display: flex;
     flex-direction: column;
     height: 100vh;
     width: calc(100vw - 20%);
   }

   .chat-header {
     height: 70px;
     flex-shrink: 0;
     border-bottom: 1px solid #ccc;
     padding-left: 10px;
     padding-right: 20px;
     display: flex;
     flex-direction: column;
     justify-content: center;
   }

   .chat-header h3 {
     margin-bottom: 0;
     text-align: center;
   }

   .chat-messages {
     flex-grow: 1;
     overflow-y: scroll;
     display: flex;
     flex-direction: column;
     justify-content: flex-end;
     margin-bottom: 0;
     min-height: min-content;
   }

   .message {
     padding-left: 20px;
     padding-right: 20px;
     margin-bottom: 10px;
     display: flex;
     justify-content: space-between;
     align-items: flex-start;
   }

   .message span {
     display: block;
     text-align: left;
   }

   .message .user-id {
     font-weight: bold;
   }

   .message-form {
     border-top: 1px solid #ccc;
   }

   .message-form, .message-input {
     width: 100%;
     margin-bottom: 0;
   }

   input[type=“text”].message-input {
     height: 50px;
     border: none;
     padding-left: 20px;
   }

Create a basic chat application

Let’s set up a basic chat interface so that we can add the functionality to show the unread message count. The code below should be straight-forward enough to understand if you’ve worked with Chatkit before:

   // src/App.js

   import React, { Component } from “react”;
   import {
     handleInput,
     connectToChatkit,
     connectToRoom,
     sendMessage,
   } from “./methods”;

   import “skeleton-css/css/normalize.css”;
   import “skeleton-css/css/skeleton.css”;
   import “./App.css”;

   class App extends Component {
     constructor() {
       super();
       this.state = {
         userId: “”,
         currentUser: null,
         currentRoom: null,
         rooms: [],
         messages: [],
         newMessage: “”,
       };

       this.handleInput = handleInput.bind(this);
       this.connectToChatkit = connectToChatkit.bind(this);
       this.connectToRoom = connectToRoom.bind(this);
       this.sendMessage = sendMessage.bind(this);
     }

     render() {
       const {
         rooms,
         currentRoom,
         currentUser,
         messages,
         newMessage,
       } = this.state;

       const roomList = rooms.map(room => {
         const isRoomActive = room.id === currentRoom.id ? ‘active’ : ‘’;
         return (
           <li
              className={isRoomActive}
              key={room.id}
              onClick={() => this.connectToRoom(room.id)}
            >
              <span className=“room-name”>{room.name}</span>
            </li>
         );
       });

       const messageList = messages.map(message => {
         const arr = message.parts.map(p => {
             return (
               <span className=“message-text”>{p.payload.content}</span>
             );
         });

         return (
           <li className=“message” key={message.id}>
              <div>
                <span className=“user-id”>{message.senderId}</span>
                {arr}
              </div>
            </li>
         )
       });

       return (
         <div className=“App”>
           <aside className=“sidebar left-sidebar”>
             {!currentUser ? (
                 <div className=“login”>
                   <h3>Join Chat</h3>
                   <form id=“login” onSubmit={this.connectToChatkit}>
                     <input
                       onChange={this.handleInput}
                       className=“userId”
                       type=“text”
                       name=“userId”
                       placeholder=“Enter your username”
                     />
                   </form>
                 </div>
               ) : null
             }
             {currentRoom ? (
               <div className=“room-list”>
                 <h3>Rooms</h3>
                 <ul className=“chat-rooms”>
                   {roomList}
                 </ul>
               </div>
               ) : null
             }
           </aside>
           {
             currentUser ? (
               <section className=“chat-screen”>
                 <ul className=“chat-messages”>
                   {messageList}
                 </ul>
                 <footer className=“chat-footer”>
                   <form onSubmit={this.sendMessage} className=“message-form”>
                     <input
                       type=“text”
                       value={newMessage}
                       name=“newMessage”
                       className=“message-input”
                       placeholder=“Type your message and hit ENTER to send”
                       onChange={this.handleInput}
                     />
                   </form>
                 </footer>
               </section>
             ) : null
           }
         </div>
       );
     }
   }

   export default App;

Create a new methods.js file within the src directory and add the following code into it:

   // src/methods.js

   import { ChatManager, TokenProvider } from “@pusher/chatkit-client”;

   function handleInput(event) {
     const { value, name } = event.target;

     this.setState({
       [name]: value
     });
   }

   function connectToChatkit(event) {
     event.preventDefault();
     const { userId } = this.state;

     const tokenProvider = new TokenProvider({
       url:
         “<test token provider endpoint>”
     });

     const chatManager = new ChatManager({
       instanceLocator: “<your chatkit instance locator>”,
       userId,
       tokenProvider
     });

     return chatManager
       .connect()
       .then(currentUser => {
         this.setState(
           {
             currentUser,
           },
           () => connectToRoom.call(this)
         );
       })
       .catch(console.error);
   }

   function connectToRoom(roomId = “<your chatkit room id>”) {
     const { currentUser } = this.state;
     this.setState({
       messages: []
     });

     return currentUser
       .subscribeToRoomMultipart({
         roomId,
         messageLimit: 10,
         hooks: {
           onMessage: message => {
             this.setState({
               messages: […this.state.messages, message],
             });
           },
         }
       })
       .then(currentRoom => {
         this.setState({
           currentRoom,
           rooms: currentUser.rooms,
         });
       })
       .catch(console.error);
   }

   function sendMessage(event) {
     event.preventDefault();
     const { newMessage, currentUser, currentRoom } = this.state;
     const parts = [];

     if (newMessage.trim() === “”) return;

     parts.push({
       type: “text/plain”,
       content: newMessage
     });

     currentUser.sendMultipartMessage({
       roomId: ${currentRoom.id},
       parts
     });

     this.setState({
       newMessage: “”,
     });
   }

   export {
     handleInput,
     connectToRoom,
     connectToChatkit,
     sendMessage,
   }

Make sure to replace the <test token provider endpoint>, <your chatkit instance locator> and <your chatkit room id> placeholders above with the appropriate values from your Chatkit dashboard.

Open the app in a few different tabs and join the chatroom under different usernames. Send a few messages for each user. It should work just fine, similar to the GIF below:

Show the unread message count

Chatkit provides an unreadCount property that we can hook into to display the number of unread messages for the current user in a room. But how do we know when a user has read a message? This is where read cursors come in.

When a user enters a room, messages in the room are loaded into the chat interface according to the messageLimit property. At this point, it is safe to say that the user has read all the messages in that room and we can indicate this by setting a read cursor on the last message.

Change the onMessage hook in the connectToRoom function as follows:

   // src/methods.js

   function connectToRoom(roomId = “21431542”) {
     const { currentUser } = this.state;
     this.setState({
       messages: []
     });

     return currentUser
       .subscribeToRoomMultipart({
         roomId,
         messageLimit: 10,
         hooks: {
           onMessage: message => {
             this.setState({
               messages: […this.state.messages, message],
             });

             const { currentRoom } = this.state;

             if (currentRoom === null) return;

             return currentUser.setReadCursor({
               roomId: currentRoom.id,
               position: message.id,
             });
           },
         }
       })
       .then(currentRoom => {
         this.setState({
           currentRoom,
           rooms: currentUser.rooms,
         });
       })
       .catch(console.error);
   }

What this means is that, if the user leaves the room by any means (such as by going offline, or switching to another room) any messages sent after the last read cursor position would count towards the unreadCount.

We can then use the onRoomUpdated connection hook to update the room in the application state and display the unread count in the chat interface. Add the hook as shown below:

   // src/methods.js

   function connectToChatkit(event) {
     // […]

     return chatManager
       .connect({
         onRoomUpdated: room => {
           const { rooms } = this.state;
           const index = rooms.findIndex(r => r.id === room.id);
           rooms[index] = room;
           this.setState({
             rooms,
           });
         }
       })
       .then(currentUser => {
         this.setState(
           {
             currentUser,
           },
           () => connectToRoom.call(this)
         );
       })
       .catch(console.error);
   }

Finally, we want to display a room’s unread count if the number of unread messages is greater than zero. Update the roomList variable in the render() method of our chat app as shown below:

   // src/App.js

   const roomList = rooms.map(room => {
     const isRoomActive = room.id === currentRoom.id ? ‘active’ : ‘’;
     return (
       <li
          className={isRoomActive}
          key={room.id}
          onClick={() => this.connectToRoom(room.id)}
        >
          <span className=“room-name”>{room.name}</span>
          {room.unreadCount > 0 ? (
            <span className=“room-unread”>{room.unreadCount}</span>
          ): null}
        </li>
     );
   }); 

You can simulate unread messages by creating a different room and switching to it as one user, then send messages to the first room as another user. It will display the unread count for any of the users as appropriate:

Wrap up

In this tutorial, you learned how add unread message count to your Chatkit app. We explored how to use read cursors to determine if a user has read a message, and how to display the number of unread messages in the application interface.

You can checkout other things Chatkit can do by viewing its extensive documentation. Don’t forget to grab the complete source code in this GitHub repository.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about React

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

Best 50 React Interview Questions for Frontend Developers in 2019

JavaScript Basics Before You Learn React

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Reactjs vs. Angularjs — Which Is Best For Web Development

React + TypeScript : Why and How

How To Write Better Code in React

React Router: Add the Power of Navigation

Getting started with React Router

Using React Router for optimizing React apps


#reactjs #javascript #css #node-js #chatbot

What is GEEK

Buddha Community

How to show unread message count with React
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Mathew Rini

1615544450

How to Select and Hire the Best React JS and React Native Developers?

Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.

What is React.js?

Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.

React vs React Native

  • React Native is a platform that uses a collection of mobile-specific components provided by the React kit, while React.js is a JavaScript-based library.
  • React.js and React Native have similar syntax and workflows, but their implementation is quite different.
  • React Native is designed to create native mobile apps that are distinct from those created in Objective-C or Java. React, on the other hand, can be used to develop web apps, hybrid and mobile & desktop applications.
  • React Native, in essence, takes the same conceptual UI cornerstones as standard iOS and Android apps and assembles them using React.js syntax to create a rich mobile experience.

What is the Average React Developer Salary?

In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.

* React.js Developer Salary by Country

  • United States- $120,000
  • Canada - $110,000
  • United Kingdom - $71,820
  • The Netherlands $49,095
  • Spain - $35,423.00
  • France - $44,284
  • Ukraine - $28,990
  • India - $9,843
  • Sweden - $55,173
  • Singapore - $43,801

In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.

However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.

It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.

As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.

How to Hire React.js Developers?

  • Conduct thorough candidate research, including portfolios and areas of expertise.
  • Before you sit down with your interviewing panel, do some homework.
  • Examine the final outcome and hire the ideal candidate.

Why is React.js Popular?

React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.

React is scalable. it utilises a single language, For server-client side, and mobile platform.

React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.

React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.

Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.

Final thoughts:

As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.

If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation

#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Aria Barnes

Aria Barnes

1627031571

React 18: Things You Need To Know About React JS Latest Version

The most awaited version of React 18 is finally out now. Its team has finally revealed the alpha version of React 18 and its plan, though the official launch is still pending. This time the team has tried something and released the plan first to know their user feedback because the last version of React 17 was not that much appreciated among developers.

According to Front-end Frameworks SurveyReact JS has ranked top in the list of most loved frameworks. Thus, the developer communities expect a bit higher from the framework, so they are less appreciative of the previous launch.
ReactJS stats.pngSo, this time React 18 will be a blast. For beginners, the team is working on a new approach. They have called a panel of experts, library authors, educators, and developers to take part in a working group. Initially, it will be a small group.

I am not a part of this release but following the team on their GitHub discussion group. After gathering the information from there, I can say that they have planned much better this time.

React 17 was not able to meet the developer's community. The focus was all primarily centered on making it easier to upgrade React itself. React 18 release will be the opposite. It has a lot of features for react developers.

Read more here: React 18: Things You Need To Know About React JS Latest Version

#hire react js developers #hire react js developers india #react developers india #react js developer #react developer #hire react developers

Aubrey  Price

Aubrey Price

1589722410

Build a simple React Native Pokemon app with React-Navigation

As we start learning new technologies we want to start building something or work on a simple project to get a better understanding of the technology. So, let’s build this simple app.
For this app, we will be using PokeApi to get our pokemon data, and also we will be using Hooks. I am using pokemondb for pokemon sprites. It’s just a personal preference you can use whatever you want.

#react-native #react-native-app #react-navigation #react-native-development #react