# React JS

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:**

**Step 1: Create a React Application**

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

```bash
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:

```bash
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="/files/RBrS121HwoicHPsNpGE9" alt=""><figcaption></figcaption></figure>

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

## **Add ReferralHero Global Tracking Code**

#### **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:

<pre class="language-html" data-title="public/index.html" data-overflow="wrap" data-line-numbers><code class="lang-html">&#x3C;!DOCTYPE html>
&#x3C;html lang="en">
  &#x3C;head>
    &#x3C;title>React App&#x3C;/title>
    
<strong>&#x3C;!-- start ReferralHero code -->
</strong><strong>    &#x3C;script>
</strong><strong>      !function(m,a,i,t,r,e){if(m.RH)return;r=m.RH={},r.uuid
</strong><strong>      =t,r.loaded=0,r.base_url=i,r.queue=[],m.rht=function()
</strong><strong>      {r.queue.push(arguments)};e=a.getElementsByTagName('script')
</strong><strong>      [0],c=a.createElement('script');c.async=!0,c.src=
</strong><strong>      'https://referralhero-global-code.s3.amazonaws.com/'+'production'+
</strong><strong>      '/'+t+'.js',e.parentNode.insertBefore(c,e)}(window,document,
</strong><strong>      'https://app.referralhero.com/','RHxxxxxxxxx');  
</strong><strong>    &#x3C;/script>
</strong><strong>&#x3C;!-- end ReferralHero code -->
</strong>
  &#x3C;/head>
  &#x3C;body>
    &#x3C;div id="root">&#x3C;/div>
  &#x3C;/body>
&#x3C;/html>
</code></pre>

#### **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:

<pre class="language-jsx" data-title="src/App.js" data-line-numbers><code class="lang-jsx">import { useEffect } from 'react';

function App() {

<strong>  useEffect(() => {
</strong><strong>    const script = document.createElement('script');
</strong><strong>    script.textContent = `
</strong><strong>      !function(m,a,i,t,r,e){if(m.RH)return;r=m.RH={},r.uuid
</strong><strong>      =t,r.loaded=0,r.base_url=i,r.queue=[],m.rht=function()
</strong><strong>      {r.queue.push(arguments)};e=a.getElementsByTagName('script')
</strong><strong>      [0],c=a.createElement('script');c.async=!0,c.src=
</strong><strong>      'https://referralhero-global-code.s3.amazonaws.com/'+'production'+
</strong><strong>      '/'+t+'.js',e.parentNode.insertBefore(c,e)}(window,document,
</strong><strong>      'https://app.referralhero.com/','RHxxxxxxxxx');
</strong><strong>    `;
</strong><strong>
</strong><strong>    document.body.appendChild(script);
</strong><strong>
</strong><strong>    return () => {
</strong><strong>      document.body.removeChild(script);
</strong><strong>    };
</strong><strong>  }, []);
</strong>
  return (
    &#x3C;div className="App">
      &#x3C;h1>Welcome to My App&#x3C;/h1>
    &#x3C;/div>
  );
}

export default App;
</code></pre>

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**

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.

<pre class="language-jsx" data-title="src/Dashboard.js" data-line-numbers><code class="lang-jsx">function Dashboard() {
  return (
    &#x3C;div>
<strong>      {/* Add the ReferralHero widget here */}
</strong><strong>      &#x3C;div id="referralhero-dashboard-MFxxxxxxxxxx">&#x3C;/div>
</strong>    &#x3C;/div>
  );
}

export default Dashboard;
</code></pre>

{% 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**

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

### 1) Using `RH.form.submit` Method:

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. \
For more detailed information about `RH.form.submit` and its functionalities, click [here](/referral-hero-documentation/integrations/javascript-web-api/add-a-subscriber.md).

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

<pre class="language-jsx" data-line-numbers><code class="lang-jsx">  const handleSubmit = (e) => {
    e.preventDefault();

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

</code></pre>

{% endtab %}

{% tab title="React Component " %}

<pre class="language-jsx" data-line-numbers><code class="lang-jsx">import React, { useState } from 'react';

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

<strong>  const handleSubmit = (e) => {
</strong><strong>    e.preventDefault();
</strong><strong>
</strong><strong>    const data = {
</strong><strong>      email: email,
</strong><strong>      name: name,
</strong><strong>      phone_number: phone,
</strong><strong>    };
</strong><strong>    
</strong><strong>    if (window.RH_MFxxxxxxxxx) {
</strong><strong>      window.RH_MFxxxxxxxxx.form.submit(data)
</strong><strong>      console.log("Subscriber created or tracked successfully");
</strong><strong>    } else {
</strong><strong>      console.log("Subscriber not tracked");
</strong><strong>    }
</strong><strong>  };
</strong>
  return (
<strong>    &#x3C;form onSubmit={handleSubmit}>
</strong>      &#x3C;input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        placeholder="Name" 
        required 
      />
      &#x3C;input 
        type="email" 
        value={email} 
        onChange={(e) => setEmail(e.target.value)} 
        placeholder="Email" 
        required 
      />
      &#x3C;input 
        type="text" 
        value={phone} 
        onChange={(e) => setPhone(e.target.value)} 
        placeholder="Phone Number" 
      />
      &#x3C;button type="submit">Submit&#x3C;/button>
    &#x3C;/form>
  );
};

export default Register;
</code></pre>

{% endtab %}
{% endtabs %}

### 2) Using `RH.pendingReferral` Method:

To track referrals that enter the first step of a multi-step conversion event, you can use the `RH.pendingReferral` method. For more detailed information about `RH.pendingReferral` and its functionalities, click [here](/referral-hero-documentation/integrations/javascript-web-api/add-a-pending-referral.md).

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

<pre class="language-jsx" data-line-numbers><code class="lang-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,
              };
<strong>              window.RH.pendingReferral(data);
</strong>            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
</code></pre>

{% endtab %}

{% tab title="React Component" %}

<pre class="language-jsx" data-line-numbers><code class="lang-jsx">import React, { useEffect } from 'react';

const Login = () => {

<strong>  useEffect(() => {
</strong><strong>    window.RHConfig = {
</strong><strong>      callbacks: {
</strong><strong>        ready: function () {
</strong><strong>          const form = document.getElementById("referral-form");
</strong><strong>          if (form) {
</strong><strong>            form.addEventListener("submit", function (e) {
</strong><strong>              e.preventDefault(); 
</strong><strong>              const data = {
</strong><strong>                name: form.querySelector('#name').value, 
</strong><strong>                email: form.querySelector('#email').value,
</strong><strong>              };
</strong><strong>              window.RH.pendingReferral(data);
</strong><strong>            });
</strong><strong>          }
</strong><strong>        },
</strong><strong>      },
</strong><strong>    };
</strong><strong>    return () => {
</strong><strong>      window.RHConfig = {};
</strong><strong>    };
</strong><strong>  }, []); 
</strong>
  return (
    &#x3C;form id="referral-form">
      &#x3C;input type="text" id="name" placeholder="Name" required />
      &#x3C;input type="email" id="email" placeholder="Email" required />
      &#x3C;button type="submit">Submit&#x3C;/button>
    &#x3C;/form>
  );
};

export default Login;
</code></pre>

{% endtab %}
{% endtabs %}

### 3) Using `RH.trackReferral` Method:

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](/referral-hero-documentation/integrations/javascript-web-api/track-multi-step-conversion-events.md#track-referral-conversion-event-only).

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

<pre class="language-javascript" data-line-numbers><code class="lang-javascript">  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,
              };
<strong>              window.RH.trackReferral(email, data);
</strong>            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
</code></pre>

{% endtab %}

{% tab title="React component" %}

<pre class="language-jsx" data-line-numbers><code class="lang-jsx">import React, { useEffect } from 'react';

const Refer = () => {

<strong>  useEffect(() => {
</strong><strong>    window.RHConfig = {
</strong><strong>      callbacks: {
</strong><strong>        ready: function () {
</strong><strong>          const form = document.getElementById("refer-form");
</strong><strong>          if (form) {
</strong><strong>            form.addEventListener("submit", function (e) {
</strong><strong>              e.preventDefault(); 
</strong><strong>              const email = form.querySelector('#email').value;
</strong><strong>              const data = {
</strong><strong>                name: form.querySelector('#name').value, 
</strong><strong>                transaction_id: form.querySelector('#transaction_id').value,
</strong><strong>              };
</strong><strong>              window.RH.trackReferral(email, data);
</strong><strong>            });
</strong><strong>          }
</strong><strong>        },
</strong><strong>      },
</strong><strong>    };
</strong><strong>    return () => {
</strong><strong>      window.RHConfig = {};
</strong><strong>    };
</strong><strong>  }, []); 
</strong>
  return (
    &#x3C;form id="refer-form">
      &#x3C;input type="text" id="name" placeholder="Name" required />
      &#x3C;input type="email" id="email" placeholder="Email" required />
      &#x3C;input type="text" id='transaction_id' placeholder="Transaction ID" required />
      &#x3C;button type="submit">Submit&#x3C;/button>
    &#x3C;/form>
  );
};

export default Refer;
</code></pre>

{% endtab %}
{% endtabs %}

### 4) Using `RH.organicTrackReferral` Method:

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](/referral-hero-documentation/integrations/javascript-web-api/track-multi-step-conversion-events.md#track-referral-conversion-event-or-add-an-organic-subscriber).

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

<pre class="language-jsx" data-line-numbers><code class="lang-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,
              };
<strong>              window.RH_MFxxxxxxxxxxx.organicTrackReferral( data);
</strong>            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
</code></pre>

{% endtab %}

{% tab title="React Component" %}

<pre class="language-jsx" data-line-numbers><code class="lang-jsx">import React, { useEffect } from 'react';

const Refer = () => {

<strong>  useEffect(() => {
</strong><strong>    window.RHConfig = {
</strong><strong>      callbacks: {
</strong><strong>        ready: function () {
</strong><strong>          const form = document.getElementById("organic-referral-form");
</strong><strong>          if (form) {
</strong><strong>            form.addEventListener("submit", function (e) {
</strong><strong>              e.preventDefault(); 
</strong><strong>              const data = {
</strong><strong>                name: form.querySelector('#name').value, 
</strong><strong>                email: form.querySelector('#email').value,
</strong><strong>                phone_number: form.querySelector('#phone').value,
</strong><strong>              };
</strong><strong>              window.RH_MFxxxxxxxxxx.organicTrackReferral( data);
</strong><strong>            });
</strong><strong>          }
</strong><strong>        },
</strong><strong>      },
</strong><strong>    };
</strong><strong>    return () => {
</strong><strong>      window.RHConfig = {};
</strong><strong>    };
</strong><strong>  }, []); 
</strong>
  return (
    &#x3C;form id="organic-referral-form">
      &#x3C;input type="text" id="name" placeholder="Name" required />
      &#x3C;input type="email" id="email" placeholder="Email" required />
      &#x3C;input type="text" id='phone' placeholder="Phone" required/>
      &#x3C;button type="submit">Submit&#x3C;/button>
    &#x3C;/form>
  );
};

export default Refer;
</code></pre>

{% 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.&#x20;

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

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

<pre class="language-javascript" data-line-numbers><code class="lang-javascript">  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,
                };
<strong>              window.RH_MFxxxxxxxxxx.trackTransaction(data);
</strong>            });
          }
        },
      },
    };
    return () => {
      window.RHConfig = {};
    };
  }, []); 
</code></pre>

{% endtab %}

{% tab title="React Component" %}

<pre class="language-jsx" data-line-numbers><code class="lang-jsx">import React, { useEffect } from 'react';

const Transaction = () => {

<strong>  useEffect(() => {
</strong><strong>    window.RHConfig = {
</strong><strong>      callbacks: {
</strong><strong>        ready: function () {
</strong><strong>          const form = document.getElementById("transaction-form");
</strong><strong>          if (form) {
</strong><strong>            form.addEventListener("submit", function (e) {
</strong><strong>              e.preventDefault(); 
</strong><strong>              const data = {
</strong><strong>                  email: form.querySelector('#email').value,
</strong><strong>                  amount: form.querySelector('#amount').value,
</strong><strong>                  product_id: form.querySelector('#product_id').value,
</strong><strong>                  transaction_id: form.querySelector('#transaction_id').value,
</strong><strong>                };
</strong><strong>              window.RH_MFxxxxxxxxxx.trackTransaction(data);
</strong><strong>            });
</strong><strong>          }
</strong><strong>        },
</strong><strong>      },
</strong><strong>    };
</strong><strong>    return () => {
</strong><strong>      window.RHConfig = {};
</strong><strong>    };
</strong><strong>  }, []); 
</strong>
  return (
    &#x3C;form id="transaction-form">
      &#x3C;input type="email" id="email" placeholder="Email" required />
      &#x3C;input type="number" id="amount" placeholder="Amount" required />
      &#x3C;input type="text" id="product_id" placeholder="Product ID" required />
      &#x3C;input type="text" id="transaction_id" placeholder="Transaction ID" required /> 
      &#x3C;button type="submit">Submit&#x3C;/button>
    &#x3C;/form>
  );
};

export default Transaction;
</code></pre>

{% 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://berylsystems.gitbook.io/referral-hero-documentation/integrations/react-js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
