How to add push notification feature in ReactJS ?
In this article, we will learn how to add a push-on notification feature in a react application using an npm package React-push-notification.
Features of React-push-notification:
- Lightweight module
- Very easy to use
Creating React application and Module installation:
Step 1: Create a React application using the following command:
npx create-react-app project
Step 2: After creating your project folder(i.e. project), move to it by using the following command:
Step 3: now install the dependency react-push-notification by using the following command:
npm i react-push-notification
Project Structure: It will look like this.
Example: We need to add Notifications that we import from the module at the top of the other components. This acts as the container for the notification then we need to import addNotification method from ‘react-push-notification’ the method acts on a number of parameters that change our notification like title, color, etc.
Filename: App.js: We are creating a simple button named push notification which triggers the onclick function buttonOnClick that calls the method addNotification here I have added the title as ‘Warning’ and native as true. The native option is by default false, this native property turns the notification into a native web notification.
Step to Run Application: Run the application using the following command from the root directory of the project.
We can further create our own notifications with different colors and styles.
In this example, let’s create a warning and a success notification.
We are creating a simple form that will have a single input field name and a submit button. If we click on submit without entering a name we get a warning notification and we will get success if we fill the name field.
We are creating a name state using react hook useState.In the input field, we are creating an OnChange function that stores the value in the state.
For the submit button in the form we are creating an onClick function that checks if the name state is empty or not. If empty it triggers function warningNotification or else triggers successNotification. For both the notifications, we have added titles, messages, subtitles and even have changed colors.