0

How would one go about making global functions in React that you only have to import into one file that shares it across every page?

Right now I can have to import helper.tsx into each file where I want to use them in.

For example I have a helper.tsx file that exports functions as such:

interface cookieProps {
  name: string;
  value: string;
  exdays: number;
}
export const getCookie = ({ name }: cookieProps) => {
  var i,
    x,
    y,
    ARRcookies = document.cookie.split(";");
  for (i = 0; i < ARRcookies.length; i++) {
    x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
    y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
    x = x.replace(/^\s+|\s+$/g, "");
    if (x == name) {
      return unescape(y);
    }
  }
  return "";
};

Now were I do import it into my App.tsx file like this:

import React, { useEffect } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import Cards from "./pages/Cards";
import { getCookie } from "./controllers/helpers";

const theme = createTheme({
  palette: {
    primary: {
      main: "#fff",
    },
    secondary: {
      main: "#f8f8f8",
    },
  })
export default function App() {
  return (
    <ThemeProvider theme={theme}>
        <BrowserRouter>
          <Navbar />
          <Routes>
            <Route path="/home" element={<Home />} />
            <Route path="/cards" element={<Cards />} />
            <Route path="*" element={<Home />} />
          </Routes>
          <Footer />
        </BrowserRouter>
    </ThemeProvider>
  );
}

I cannot call it from Home or Cards etc. When declared cookie imports are not initialised or used inside App.tsx I cannot access them. I want to be able to call all of those helper functions from every page possible and not have to import them again.

Should I make the imports into vars and call them as helper.getCookie?

  • If you're going to deviate from the module pattern and make global functions, then be sure to document them well for the next developer. – Emiel Zuurbier Jan 30 '23 at 10:26

1 Answers1

0

Bind that function into window, like window.getCookie = getCookie, or add to a helper object like window.helper = {getCookie() {...}}

p/s: I am using this method, not sure if that is a right way to do or if it affects whole website performance, but no problems so far

Dave Runner
  • 226
  • 1
  • 5