Jack23
Jack23

Reputation: 1396

ReactJS: Redirect to homepage

I'm using react-router-dom, and I have a problem to redirect to the homepage (path="/").

Basically, I have a form with a submit button. When it is clicked I would to do the redirect.

const saveEntity = (event, errors, values) => {
    console.log('values .', values);
    if (values.realm) {
      setRealm(values.realm);
    }
    if (values.ente) {
      setEnte(values.ente);
    }
    if (values.realm) {
      console.log('dentro ', values.realm);
      // const history = useHistory();
      // const handler = () => {
      //   history.push('/');
      // };
      // return <Redirect to={{ pathname: '/' }} />;
    }
  };

return (
    <div>
      <AvForm  onSubmit={saveEntity}>
// .....

in the saveEntity I have tried to use history.push or Redirect, but nothing happens when I click the button.

How can I fix?

Thank you

Upvotes: 0

Views: 129

Answers (1)

Nokwiw
Nokwiw

Reputation: 396

You don't need to use a handler, just history.push('/'). and you have to call useHistory() in the root of YourComponent as bellow

const YourComponnt = ()=>{
const history = useHistory();

const saveEntity = (event, errors, values) => {
    console.log('values .', values);
    if (values.realm) {
      setRealm(values.realm);
    }
    if (values.ente) {
      setEnte(values.ente);
    }
    if (values.realm) {
      console.log('dentro ', values.realm);
    }

   history.push('/'); // or history.replace('/');
  };

return (
    <div>
      <AvForm  onSubmit={saveEntity}>
// .....
}

Upvotes: 1

Related Questions