# ReactJS

In this section, we will review the different methods to include the ReferralHero external JavaScript library in a ReactJS project.

{% hint style="info" %}
**Please Note:**

* `RH_MFxxxxxxxxxxx` are placeholders for your campaign's UUID, which you will need to replace with your actual campaign UUID.
  {% endhint %}

## **Create and Set Up the React Application:** <a href="#create-and-set-up-the-react-application" id="create-and-set-up-the-react-application"></a>

**Step 1: Create a React Application**

Open your terminal or command prompt and use the following command to create a new React app:

```jsdoc
npx create-react-app name_of_the_app
```

**Step 2: Navigate to the Application Directory**

After the application has been created, navigate to the project directory using:

```
cd name_of_the_app
```

**Step 3: Open the Project Structure**

Navigate through the default structure generated by `create-react-app`. The main file you’ll be working with is `App.js` located in the `src` folder & can design your custom pages.

<figure><img src="https://363135598-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LsuqexOLPOWiUrWg_Ko%2Fuploads%2F62PdM0WGb387PNr5xdgZ%2Fimage.png?alt=media&#x26;token=289383f2-6e90-419b-85bd-07dec81cc591" alt=""><figcaption></figcaption></figure>

Now you're ready to start adding your custom code or configurations!

## **Add ReferralHero Global Tracking Code** <a href="#add-referralhero-global-tracking-code" id="add-referralhero-global-tracking-code"></a>

**Option 1: Add in** `public/index.html`

1. Navigate to the `public` folder in your React application.
2. Open `index.html`.
3. Inside the `<head>` section, add the ReferralHero tracking script:

{% tabs %}
{% tab title="public/index.html" %}

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React App</title>
    
<!-- start ReferralHero code -->
    <script>
      !function(m,a,i,t,r,e){if(m.RH)return;r=m.RH={},r.uuid
      =t,r.loaded=0,r.base_url=i,r.queue=[],m.rht=function()
      {r.queue.push(arguments)};e=a.getElementsByTagName('script')
      [0],c=a.createElement('script');c.async=!0,c.src=
      'https://referralhero-global-code.s3.amazonaws.com/'+'production'+
      '/'+t+'.js',e.parentNode.insertBefore(c,e)}(window,document,
      'https://app.referralhero.com/','RHxxxxxxxxx');  
    </script>
<!-- end ReferralHero code -->

  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
```

{% endtab %}
{% endtabs %}

**Option 2: Add in `src/App.js` (Root File)**

1. Open `src/App.js` in your React app.
2. Inside the `useEffect` hook, include the script dynamically:

{% tabs %}
{% tab title="src/App.js" %}

```javascript
import { useEffect } from 'react';

function App() {

  useEffect(() => {
    const script = document.createElement('script');
    script.textContent = `
      !function(m,a,i,t,r,e){if(m.RH)return;r=m.RH={},r.uuid
      =t,r.loaded=0,r.base_url=i,r.queue=[],m.rht=function()
      {r.queue.push(arguments)};e=a.getElementsByTagName('script')
      [0],c=a.createElement('script');c.async=!0,c.src=
      'https://referralhero-global-code.s3.amazonaws.com/'+'production'+
      '/'+t+'.js',e.parentNode.insertBefore(c,e)}(window,document,
      'https://app.referralhero.com/','RHxxxxxxxxx');
    `;

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  return (
    <div className="App">
      <h1>Welcome to My App</h1>
    </div>
  );
}

export default App;
```

{% endtab %}
{% endtabs %}

Both methods will enable the ReferralHero script in your React application. Use the one that fits best with your project structure!

## **Installing the ReferralHero Widget** <a href="#installing-the-referralhero-widget" id="installing-the-referralhero-widget"></a>

You have the flexibility to add the ReferralHero widget to specific components or pages of your application. Since the global tracking script is already included in the root file, you don’t need to add it again on each page.

### **Steps to Install the Widget**

1. **Choose the Widget to Install**

* ReferralHero provides multiple widget types, such as the Signup Widget, Dashboard Widget, and Sharing Widget.
* You can select the appropriate widget based on your campaign goals.

2. **Insert the Widget's HTML Element**

* After adding the tracking script, include the widget's HTML code into your React component where you want the widget to appear. You need to replace the placeholder `MFxxxxxxxxxx` with your campaign's UUID.

3. **Code Example: Adding a widget in a component**:

* For example , here we have added the advocate dashboard widget in newly created dashboard component. You can add it wherever you want.

{% tabs %}
{% tab title="src/Dashboard.js" %}

```javascript
function Dashboard() {
  return (
    <div>
      {/* Add the ReferralHero widget here */}
      <div id="referralhero-dashboard-MFxxxxxxxxxx"></div>
    </div>
  );
}

export default Dashboard;
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Note:** The `MFxxxxxxxxxx` is a placeholder and should be replaced with your campaign's UUID.
{% endhint %}

## **Adding ReferralHero Custom Methods for Tracking User Actions** <a href="#adding-referralhero-custom-methods-for-tracking-user-actions" id="adding-referralhero-custom-methods-for-tracking-user-actions"></a>

To utilize custom methods like `RH.form.submit` ,`RH.trackReferral` , etc in your React application, follow these steps:

### 1) Using `RH.form.submit` Method: <a href="#id-1-using-rh.form.submit-method" id="id-1-using-rh.form.submit-method"></a>

The `RH.form.submit` method allows you to add subscribers to your referral campaign directly from your forms. This integration simplifies the signup process for your users, making it easy for them to join your referral program.&#x20;

For more detailed information about `RH.form.submit` and its functionalities, click [here](https://berylsystems.gitbook.io/referral-hero-documentation/integrations/javascript-web-api/add-a-subscriber).

{% tabs %}
{% tab title="Method" %}

```javascript
const handleSubmit = (e) => {
    e.preventDefault();

    const data = {
      email: email,
      name: name,
      phone_number: phone,
    };
    
    if (window.RH_MFxxxxxxxx) {
      window.RH_MFxxxxxxxxx.form.submit(data)
      console.log("Subscriber created or tracked successfully");
    } else {
      console.log("Subscriber not tracked");
    }
  };
```

{% endtab %}

{% tab title="React Component" %}

```jsx
import React, { useState } from 'react';

const Register = () => {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    const data = {
      email: email,
      name: name,
      phone_number: phone,
    };
    
    if (window.RH_MFxxxxxxxxx) {
      window.RH_MFxxxxxxxxx.form.submit(data)
      console.log("Subscriber created or tracked successfully");
    } else {
      console.log("Subscriber not tracked");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        placeholder="Name" 
        required 
      />
      <input 
        type="email" 
        value={email} 
        onChange={(e) => setEmail(e.target.value)} 
        placeholder="Email" 
        required 
      />
      <input 
        type="text" 
        value={phone} 
        onChange={(e) => setPhone(e.target.value)} 
        placeholder="Phone Number" 
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Register;
```

{% endtab %}
{% endtabs %}

### 2) Using `RH.pendingReferral` Method: <a href="#id-2-using-rh.pendingreferral-method" id="id-2-using-rh.pendingreferral-method"></a>

To track referrals that enter the first step of a multi-step conversion event, you can use the `RH.pendingReferral` method.&#x20;

For more detailed information about `RH.pendingReferral` and its functionalities, click [here](https://berylsystems.gitbook.io/referral-hero-documentation/integrations/javascript-web-api/add-a-pending-referral).

{% tabs %}
{% tab title="Method" %}

```jsx
useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("referral-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const data = {
                name: form.querySelector('#name').value, 
                email: form.querySelector('#email').value,
              };
              window.RH.pendingReferral(data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
```

{% endtab %}

{% tab title="React Component" %}

```jsx
import React, { useEffect } from 'react';

const Login = () => {

  useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("referral-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const data = {
                name: form.querySelector('#name').value, 
                email: form.querySelector('#email').value,
              };
              window.RH.pendingReferral(data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 

  return (
    <form id="referral-form">
      <input type="text" id="name" placeholder="Name" required />
      <input type="email" id="email" placeholder="Email" required />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Login;
```

{% endtab %}
{% endtabs %}

### 3) Using `RH.trackReferral` Method: <a href="#id-3-using-rh.trackreferral-method" id="id-3-using-rh.trackreferral-method"></a>

The `RH.trackReferral` method is used to track referrals or add them to a campaign if they already exist as "Pending." If a referral is recognized through cookies, a new referral will automatically be created in the appropriate campaign. If the user is not a referral, no action will be taken by the system.

For more detailed information about `RH.trackReferral` and its functionalities, click [here](https://berylsystems.gitbook.io/referral-hero-documentation/integrations/javascript-web-api/track-multi-step-conversion-events#track-referral-conversion-event-only).

{% tabs %}
{% tab title="Method" %}

```jsx
useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("refer-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const email = form.querySelector('#email').value;
              const data = {
                name: form.querySelector('#name').value, 
                transaction_id: form.querySelector('#transaction_id').value,
              };
              window.RH.trackReferral(email, data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
```

{% endtab %}

{% tab title="React Component" %}

```jsx
import React, { useEffect } from 'react';

const Refer = () => {

  useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("refer-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const email = form.querySelector('#email').value;
              const data = {
                name: form.querySelector('#name').value, 
                transaction_id: form.querySelector('#transaction_id').value,
              };
              window.RH.trackReferral(email, data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 

  return (
    <form id="refer-form">
      <input type="text" id="name" placeholder="Name" required />
      <input type="email" id="email" placeholder="Email" required />
      <input type="text" id='transaction_id' placeholder="Transaction ID" required />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Refer;
```

{% endtab %}
{% endtabs %}

### 4) Using `RH.organicTrackReferral` Method: <a href="#id-4-using-rh.organictrackreferral-method" id="id-4-using-rh.organictrackreferral-method"></a>

The `RH.organicTrackReferral` function is used to track referrals or add organic subscribers to your ReferralHero campaign on the conversion page. This function ensures that both referred and non-referred users are accurately tracked and recorded in your campaign.

For more detailed information about `RH.organicTrackReferral` and its functionalities, click [here](https://berylsystems.gitbook.io/referral-hero-documentation/integrations/javascript-web-api/track-multi-step-conversion-events#track-referral-conversion-event-or-add-an-organic-subscriber).

{% tabs %}
{% tab title="Method" %}

```jsx
useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("organic-referral-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const data = {
                name: form.querySelector('#name').value, 
                email: form.querySelector('#email').value,
                phone_number: form.querySelector('#phone').value,
              };
              window.RH_MFxxxxxxxxxxx.organicTrackReferral( data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
```

{% endtab %}

{% tab title="React Component" %}

```jsx
import React, { useEffect } from 'react';

const Refer = () => {

  useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("organic-referral-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const data = {
                name: form.querySelector('#name').value, 
                email: form.querySelector('#email').value,
                phone_number: form.querySelector('#phone').value,
              };
              window.RH_MFxxxxxxxxxx.organicTrackReferral( data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 

  return (
    <form id="organic-referral-form">
      <input type="text" id="name" placeholder="Name" required />
      <input type="email" id="email" placeholder="Email" required />
      <input type="text" id='phone' placeholder="Phone" required/>
      <button type="submit">Submit</button>
    </form>
  );
};

export default Refer;
```

{% endtab %}
{% endtabs %}

### 5) Using `RH.trackTransaction` Method:

This method allows you to track transactions by passing relevant transaction data such as the amount, product ID, and customer email.

For more detailed information about `RH.trackTransaction` and its functionalities, click [here](https://berylsystems.gitbook.io/referral-hero-documentation/integrations/javascript-web-api/track-transaction).

{% tabs %}
{% tab title="Method" %}

```jsx
useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("transaction-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const data = {
                  email: form.querySelector('#email').value,
                  amount: form.querySelector('#amount').value,
                  product_id: form.querySelector('#product_id').value,
                  transaction_id: form.querySelector('#transaction_id').value,
                };
              window.RH_MFxxxxxxxxxx.trackTransaction(data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
```

{% endtab %}

{% tab title="React Component" %}

```jsx
import React, { useEffect } from 'react';

const Transaction = () => {

  useEffect(() => {
    window.RHConfig = {
      callbacks: {
        ready: function () {
          const form = document.getElementById("transaction-form");
          if (form) {
            form.addEventListener("submit", function (e) {
              e.preventDefault(); 
              const data = {
                  email: form.querySelector('#email').value,
                  amount: form.querySelector('#amount').value,
                  product_id: form.querySelector('#product_id').value,
                  transaction_id: form.querySelector('#transaction_id').value,
                };
              window.RH_MFxxxxxxxxxx.trackTransaction(data);
            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 

  return (
    <form id="transaction-form">
      <input type="email" id="email" placeholder="Email" required />
      <input type="number" id="amount" placeholder="Amount" required />
      <input type="text" id="product_id" placeholder="Product ID" required />
      <input type="text" id="transaction_id" placeholder="Transaction ID" required /> 
      <button type="submit">Submit</button>
    </form>
  );
};

export default Transaction;
```

{% endtab %}
{% endtabs %}

By implementing this, ReferralHero will record the transaction and handle the attribution automatically.

By leveraging these powerful methods—`form.submit`, `pendingReferral`, `trackReferral`, `organicTrackReferral`, and `trackTransaction`—you can efficiently manage user tracking, referrals, and transaction attribution in your ReferralHero campaigns.
