-2

I am trying to pass the 5 utm parameters utm_campaign, utm_term, utm_content, utm_medium, and utm_source from my client-side React app to my back-end app, which acts as an API for my React app.

I need some Javascript to simply read the UTM parameters from the window's URL (window.location.search) and append it to my fetch('...') inside of my React app

Jason FB
  • 4,752
  • 3
  • 38
  • 69

1 Answers1

1

here is a basic solution using ES6

to use simply import ParseUrlUtils from './parse_url_utils' and then add this file:


const ParseUrlUtils = {

  getParam: (name) => {
    if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(window.location.search))
    return decodeURIComponent(name[1]);
  },

  UTMPassThroughString: () => {
    const default_utms = ['utm_campaign', 'utm_term',
      'utm_source', 'utm_medium', 'utm_content']
    var utm_keys = []
    var utm_string

    default_utms.map((utm_key) => {
      utm_keys.push({key: utm_key, value: ParseUrlUtils.getParam(utm_key)})
    })
    utm_keys = utm_keys.filter((obj) => obj.value !== undefined)
    if (utm_keys.length > 0) {
      utm_string = "?" + utm_keys.map((ele) => {
        return ele.key + "=" + ele.value
      }).join("&")
    }
    return utm_string
  }
}
export default ParseUrlUtils
Jason FB
  • 4,752
  • 3
  • 38
  • 69