How to use Slack’s Incoming Webhooks in React

Posted by

The concept of webhook is simple. It works like a communicator between two applications. When we need to send automated messages or we need to send data in real-time we can use webhooks. In this tutorial, we will work with the slack webhook in our react applications.

Topics to be covered in this tutorial

  • Set up slack - Create a slack channel - Create a slack webhook
  • React project - Environment set up - Create interface - Create webhook functionality
  • Output

We will cover these topics in the tutorial and at the end of this, you will be able to use webhooks in react on your own.

Set up slack

There are many web applications that provide incoming webhooks to work with them in your own application. Such as Github, discord, slack, etc. In this tutorial, we have chosen slack. It is a popular messaging application for businesses that connects people. We will create a contact form with slack webhook. To do so, we need to follow some steps.

The first step is to sign up in the slack application. If you already have signed in then you can simply log in there. All you need to do is to visit the slack application to follow the process.

Create a slack channel

If you sign up in slack for the first time, you need to create a workspace first. In our case, we named our workspace react-webhooks-demo. Now, you will get an interface where you can create different types of channels based on different purposes.

Here, you can see that, to create a channel in slack we have just followed Add channels>create a new channel>fill the name box>create this. Now we are ready to move on to the next step.

Create a slack webhook

In this step, we are going to create a slack webhook. To do so, first, we need to find the apps from slack. Sometimes, it may visible at first In case, if you could not find it, follow the below image:

You need to click on more which is just under the Threads section and finally click on the Apps. A pop-up box will appear the moment you clicked on the apps. You will find a search option there and you need to search for incoming webhooks. You will get something like the below image:

You need to click on the Add button. It will take you to another page. There you have to click on the Add To Slack button. Now, you will find an option for adding a specific channel as a webhook. See the below image:

Here, you can see that we have selected the contact-information channel that we have created before. Now, all we need to do is to click on the Add to Incoming WebHooks integration button. It will take us to a new page with the webhook URL that we are going to use in our application. See the below image:

Now, We are ready to move on to the next step where we are going to build the contact form in react and integrate the slack webhooks.

React project

We are going to create a contact form in react. To focus on the main purpose of this tutorial we are not adding anything fancy to the UI. You can imagine it with a business application where you need to contact the client in Slack. As a matter of fact, you need to integrate slack webhooks into your react application.

In the first part, we set up slack and get the webhook URL. Now, we will set up the environment of our react application in the below section.

Environment set up

Environment setup for React Application

To work in any React application, first, we need to set up the environment for it. To do so, we need to write the below command that will create a demo react app for us. See the below command:

npx create-react-app .

This command will install react and its necessary packages in our specified folder. The npx create-react-app is doing all the stuff for us. We have just recognized our directory name with a “dot(.)” It will take some time to install all the packages depending on the internet connection. Make sure that you have connected your computer to the internet.

You will see some files like the below image after the installation process has been finished. This may be different from yours because we have removed some unnecessary stuff from this.

We need to install Axios which will help us to send the requests. To do so, follow the below command:

npm install axios

This command will install the axios library for us. Now we are ready to move on to the next step.

Create interface

In this step, we will simply create a contact form. To do so, follow the below code example:

return (
    <div className='main-area'>
      <h2>Please! Provide Your Information</h2><hr></hr>
        <form>
          <label htmlFor='name'>Name</label> <br/>
          <input id="name" type="text" placeholder="Enter Your Name"/><br/><br/>

          <label htmlFor="email">Email</label> <br/>
          <input id="email" type="email" placeholder="Enter Your Email" /><br/><br/>

          <label htmlFor="message"> Message</label> <br/>
          <textarea id="message" type="message" placeholder="Write Your Message Here"/> <br/> <br/><br/>

          <button >Submit</button>
        </form>
      </div>
  );

Here, you can see that we have created a contact form that will expect the name, email, and message from the user. We have also used some basic styling to give the UI a better look. It is not important though, you can style based on your own interests. See the below output:

If we try to fill up this form and submit it, nothing will happen. The reason is we haven’t implemented any functionality yet. In the next step, we will perform this action.

Create webhook functionality

To create webhook functionality we need to go to the app.js file. Here, we will import react, Axios, and CSS files. Later on, we will use the useState functionality to hold the data. Finally, we send the request with the help of Axios. Follow the below code example to understand it more clearly:

import React, { useState } from 'react'
import axios from 'axios'
import './App.css'

function App() {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [message, setMessage] = useState('')

  async function submitForm(e) {
    e.preventDefault();

    const webhookUrl = 'Your WebHook URL'

    const data = {
      "text": `Name: ${name} \\n${email} \\n${message}`,
    }

    let res = await axios.post(webhookUrl, JSON.stringify(data), {
      withCredentials: false,
      transformRequest: [(data) => {return data}]})

    if (res.status === 200) {
      alert("Form Submitted Successfully!")

      setName('')
      setEmail('')
      setMessage('')
    } else {
      alert("Error Occurred!")
    }

  }

  return (
    <div className='main-area'>
      <h2>Please! Provide Your Information</h2><hr></hr>
        <form>
          <label htmlFor='name'>Name</label> <br/>
          <input id="name" type="text" placeholder="Enter Your Name" value={name} onChange={(e) => { setName(e.target.value)}}/><br/><br/>

          <label htmlFor="email">Email</label> <br/>
          <input id="email" type="email" placeholder="Enter Your Email" value={email} onChange={(e) => { setEmail(e.target.value)}}/><br/><br/>

          <label htmlFor="message"> Message</label> <br/>
          <textarea id="message" type="message" placeholder="Write Your Message Here" value={message} onChange={(e) => { setMessage(e.target.value)}}/> <br/> <br/><br/>

          <button onClick={(e) => submitForm(e)}>Submit</button>
        </form>
      </div>
  );
}

export default App

Here, you may notice we have stored the webhook URL into a variable. Here, you have to put the webhook URL that you have got from the slack incoming WebHooks. After submitting the data, we also clear the text from the input field and showed a successful message. If anything went wrong, it will show the error message also.

Output

Now, it is time to test our application to check whether it is working perfectly or not. To do so, first, we need to run our application. we can do it by npm start command in our terminal.

Here, you can see that we have put some information in our contact form and clicked on the submit button. This information should appear on slack’s contact-information channel. Let’s open slack and visit the channel to see whether is there any changes occurring or not.

Here, you can see that the exact information has been shown on our channel. That means, we successfully integrated slack webhook in our react application. Now, if you need to deploy this you can use vercel or ngrok for quick deployment. Finally, this is all about working with webhooks in react.

Leave a Reply

Your email address will not be published. Required fields are marked *