Home > Back-end >  How can I invoke a callback within a React function component?
How can I invoke a callback within a React function component?

Time:02-08

This is the code I have working right now from this answer, whose comments suggested using window.history. It works, but I'd prefer to go back correctly, using React router v6.

import {useNavigate} from "react-router-dom";
import Cookies from "universal-cookie"; 

function Foo() {
  const navigate = useNavigate();
  const cookies = new Cookies();

  if (cookies.get('foo') === 'bar') {
    window.history.go(-1);
    // () => navigate(-1); // this does not work
  }
  return (
    <div />
  )
}

You can see commented out what I wanted to do, but that's not legal I think. And if I just use navigate(-1) it doesn't work, like the original question I linked.

So is there a way to use navigate inside Foo?

CodePudding user response:

() => navigate(-1); // this does not work

This defines a function which will call navigate(-1) when it is called.

You never call it.


The dirty approach is to simply not wrap it in a function, but the main render function of a component shouldn't have side effects.

Wrap it in an effect hook instead.

const Foo = () => {
  const navigate = useNavigate();
  const cookies = new Cookies();

  const foo = cookies.get('foo');

  useEffect(() => {
      if (foo === 'bar') {
          navigate(-1);
      }
  }, [foo, navigate]);

  return (
    <div />
  );
};
  •  Tags:  
  • Related