Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
how to use useLocation hook in a custom file in react js?

I have a separate file where I put the commonly used functions in my react project called MyFunctions.js . In this file, I want to use useLocation hook to get the current pathname + the query string of my current url. but it gives an error

React Hook "useLocation" is called in function "getCurrentURL" that is neither a React function component nor a custom React Hook function.

this is my code: codesandbox

// MyFunctions.js
import useLocation from "react-router-dom";

export function getUrl() {
  const location = useLocation();
  return location.pathname + location.search;
}
// App.js
import "./styles.css";
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import * as fn from "./MyFunctions";
import Test1 from "./components/Test1";

export default function App() {
  const a = fn.getUrl();

  return (
    <Router>
      <div className="App">
        <h1>Hello CodeSandbox: {a}</h1>
        <Routes>
          <Route path="/" element={<Test1 />} />
        </Routes>
      </div>
    </Router>
  );
}
// Test1.js
const Test1 = () => {
  return (
    <div>
      <h1>Lorem Ipsum</h1>
    </div>
  );
};

export default Test1;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Wrap useLocation inside curly braces in the import, like this:

import { useLocation } from "react-router-dom";

I would recommend you to rename getUrl to useGetURL to fulfil React's hook conventions.

Additionally, you have to call useLocation inside a child of <Router />. You haven't, therefore, you will get another error: useLocation() may be used only in the context of a <Router> component.

I fixed it as follows:

// App.js
import "./styles.css";
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import * as fn from "./MyFunctions";
import Test1 from "./components/Test1";

export default function App() {
  return (
    <Router>
      <YourNestedComponent />
    </Router>
  );
}

function YourNestedComponent() {
  const a = fn.useGetUrl();

  return (
    <div className="App">
      <h1>Hello CodeSandbox: {a}</h1>
      <Routes>
        <Route path="/" element={<Test1 />} />
      </Routes>
    </div>
  );
}
// MyFunctions.js
import { useLocation } from "react-router-dom";

export function useGetUrl() {
  const location = useLocation();
  return location.pathname + location.search;
}

CodeSandbox: https://codesandbox.io/s/stoic-orla-tbnb07

about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot use a hook inside a function export a hook instead like this

import {useLocation} from "react-router-dom";

export function useGetUrl() {
  const location = useLocation();
  return location.pathname + location.search;
}

And import this hook inside any component and use it like this

import {useGetUrl} from '[your_filename].js'
const url = useGetUrl()

[NOTE] You cannot call this hook directly inside JSX you have to call it on top of your component first then you can use the url inside your jsx, in whatever component you are using this hook make sure it is wrapped with <Router></Router>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda