umanga shrestha
umanga shrestha

Reputation: 406

Using Jquery code in most of the react page

I am very new to react and i had to use some lines of Jquery codes on most of the pages. For now, i have written the code on componentDidmount(), I have write this code on every other pages. That means, if i have to change something, i have to change it on all the other pages. What way would be better to put that code on a page and import that code on every page where its needed ?

This is the jquery code,

$(document).ready(function () {
      var getOffset = "";
      $('.table-responsive').on('scroll', function () {
        getOffset = $('.table').position().top;
        console.log(getOffset);
        $('.radius-wrapper').css('top', getOffset + 48);
      });
 });

Upvotes: 0

Views: 53

Answers (2)

fady sadaqah
fady sadaqah

Reputation: 11

You can use a separate file any where in your directory that includes repeated lines of code.
let we assume that you have made a file called functions.js in your project root directory like this :

function myFunction() {
    //write any lines of code here for example a console.log
    console.log("My function has been executed")
}
export { myFunction }

and then you have to import it in any file you need

import React, { Component } from "react"
import { myFunction } from "/functions"

class ComponentName extends Component {
    componentDidmount() {
        //Execute the function you imported from the functions.js here
        myFunction()
    }
    render() {
        return <h1>Hello World !</h1>
    }
}

Run the previous code and look in your console, you will find

My function has been executed

printed from the execution of myFunction you can do the same thing in other components and you will find the same result and right now you have to change the code once in functions.js and you will find the result on all components

Upvotes: 0

Red Baron
Red Baron

Reputation: 7672

I've not used jquery before but in terms of code reusability I would wrap the repeated code in a function like this:

export const myHelper = () => {
      var getOffset = "";
      $('.table-responsive').on('scroll', function () {
        getOffset = $('.table').position().top;
        console.log(getOffset);
        $('.radius-wrapper').css('top', getOffset + 48);
      });
}

and then you can import that function into every component you need it for like so:

import { myHelper } from '/utils/helper'

and then if you need to change it, you just change it inside the util library and then everywhere that imports it would have the new code

Upvotes: 2

Related Questions