umanga shrestha
umanga shrestha

Reputation: 406

Javascript to be applied on different react pages

I need to apply javascript code the most of the react page. Basically exporting from a helper file and importing on all those pages where it's needed. The following code works pretty well on a single page,

tableRadius() {
    var tableHeader = document.getElementsByTagName('thead')[0].offsetHeight;
    var topValue = this.offsetTop - this.scrollTop;
    var top = Math.round(topValue + tableHeader);

    var verticalScroll = document.querySelector(".radius-wrapper");
    verticalScroll.setAttribute("style", "top:" + top + "px");
    return;
}

componentDidMount() {
    const table = document.getElementById("dispatchTable");
    table.addEventListener("scroll", this.tableRadius);
}

After, I tried adding this code to the helper file so that i can use it accross the different pages. I don't know if i did it right but, i tried adding the tablueRadius function in a helper file but it had issues. Here it is how i did,

page.js

import { tableRadius } from '../../../services';

class Dispatcher extends Component {
  constructor(props) {
    super(props);
    this.tableRadius = tableRadius();
  }

  componentDidMount() {
    const table = document.getElementById("dispatchTable");
    table.addEventListener("scroll", this.tableRadius);
  }

}

Helper file, Services

export function tableRadius() {
  var tableHeader = document.getElementsByTagName('thead')[0].offsetHeight;
  var topValue = this.offsetTop - this.scrollTop;
  var top = Math.round(topValue + tableHeader);

  var verticalScroll = document.querySelector(".radius-wrapper");
  verticalScroll.setAttribute("style", "top:" + top + "px");

  return;  
}

Here, i get an error on helper file that says, TypeError: Cannot read property 'offsetHeight' of undefined

Am i doing it right? Or there is a bettery way? can you please suggest ?

Thank you.

Upvotes: 0

Views: 35

Answers (1)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

You're calling tableRadius in constructor. You need to just assign it.

class Dispatcher extends Component {
  constructor(props) {
    super(props);
    this.tableRadius = tableRadius;
  }

Also, along with React, prefer not to use DOM api to directly manipulate elements. Instead take advantage of React ecosystem. Write your elements inside JSX and add required listeners over there.

Upvotes: 1

Related Questions