Learner
Learner

Reputation: 13

In react how to call a function on reaching a specific URL in the browser?

I'm using window.location.href to fetch url from the browser. As soon as the specified "url" is reached, it should call the fuction abc(), somewhat like below:

if (window.location.href === "url") {
  abc(); //calls the function abc
}

function abc () {
  //code..
}

How do I do it the right way?

Upvotes: 0

Views: 801

Answers (2)

EvoluWil
EvoluWil

Reputation: 111

you can use this

useEffect(() => {
 if(window.location.href === 'url'){
  abc()
 }
},[window.location.href])

Upvotes: 2

Colin Hale
Colin Hale

Reputation: 870

I would make some hook that does that for you. Example:

const useAbcHook = () => {
  const location = useLocation()

  useEffect(() => {
   if(location.pathname === "mychoiceurl"){
    abc()
    }
  },
  [url]
}

Then to use the hook

const MyComp = () => {
  useAbcHook()
  return(<div>....</div>)
}

Upvotes: 0

Related Questions